Puzzle - Swapping Integers

Swap two integers without using a temporary storage.

Solution 1

int x = 2;
int y = 3;
x = x + y; // x = 2 + 3= 5
y = x - y; // y = 5 -3 = 2
x = x - y; // x = 5 - 2 = 3

Solution 2

Using XOR's properties -
1. 0 XOR 0 = 1 XOR 1 = 0
2. 0 XOR 1 = 1 XOR 0 = 1
3. a XOR 0 = a
4. a XOR b = b XOR a
5. a XOR (b XOR c) = (a XOR b) XOR c

int x = 2;
int y = 3;
x ^= y; // x = x XOR y
y ^= x; // y = y XOR (x XOR y) = x
x ^= y; // x = (x XOR y) XOR x = y

Obviously this solution can be extended to any data type instead of int.