Swap Two Numbers
EasyThree XORs, no temporary
Problem
Swap two integers without using a temporary variable.
Three XORs (a^=b; b^=a; a^=b) swap two numbers without any spare box.
The idea
Because XOR is its own inverse, a ^= b; b ^= a; a ^= b leaves each variable holding the other's original value. It is a classic puzzle rather than a practical technique — a temporary variable is clearer and no slower.
The trick
- Fails when both names refer to the same variable — it zeroes it.
- Modern compilers produce identical code for the obvious three-line swap.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — a=5, b=7 Values: 5, 7.
1a = a ^ b2b = a ^ b3a = a ^ bInput
- array
- [5, 7]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- a = 5, b = 9
- Output:
- a=9, b=5
- Explanation:
- XOR swapping trades values with no temp variable.
Example 2
- Input:
- a = 1, b = 2
- Output:
- a=2, b=1
- Explanation:
- They exchange places.
Example 3
- Input:
- a = 0, b = 7
- Output:
- a=7, b=0
- Explanation:
- Even with a zero it works.
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.