Created
December 5, 2022 20:31
-
-
Save iconifyit/59ca4b6386a97917d70abbb103ee8351 to your computer and use it in GitHub Desktop.
Swap two variables set to integers without using a third variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Swap two variables, set to integers, | |
// without using a third variable. | |
// Any language you want, but no Assembly. | |
// Register swaps are cheating for | |
// this riddle. | |
let x = 3 | |
let y = 5 | |
console.log(x, y) | |
// Using an array | |
x = [x,y] | |
y = x.shift() | |
x = x.pop() | |
// Using addition/subtraction | |
x = x + y | |
y = x - y | |
x = x - y | |
// Using XOR | |
x = x ^ y | |
y = x ^ y | |
x = x ^ y | |
console.log("x : " + x) | |
console.log("y : " + y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment