Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Created December 5, 2022 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/59ca4b6386a97917d70abbb103ee8351 to your computer and use it in GitHub Desktop.
Save iconifyit/59ca4b6386a97917d70abbb103ee8351 to your computer and use it in GitHub Desktop.
Swap two variables set to integers without using a third variable
// 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