README.md
December 4, 2022 ยท View on GitHub
Description
Swap two integers without using a 3rd variable!
More Info
| Submitted On | |
| By | Junaidulla |
| Level | Intermediate |
| User Rating | 4.5 (27 globes from 6 users) |
| Compatibility | Java (JDK 1.1), Java (JDK 1.2) |
| Category | Miscellaneous |
| World | Java |
| Archive File |
Source Code
Swap Two ints Without Using a Third Variable
Here's an old trick from C, which carries over to
Java. If you have two ints a and b whose
values you want to swap, the obvious way to
do so is with a third, temporary variable:
int c = a;
a = b;
b = c;
It can be done without a temporary variable,
however, using Java's bitwise xor operator ^:
a = a^b;
b = a^b;
a = a^b;
The operator ^ produces a new int, each of whose
bits is the result of xor-ing the two
corresponding bits from the operands (1 if
the bits are different, 0 otherwise). To see why the trick works, consider the single-bit case
of a=1 and b=0.
a = a^b = 1 xor 0 = 1
b = a^b = 1 xor 0 = 1
a = a^b = 1 xor 1 = 0
Even though you initially overwrite the value of
a, no information is lost; its encoding
simply changes. In the case of larger (multi-bit)
numbers, each pair of bits will be swapped
in the same way, and so the entire int values are swapped.
Finally, the swapping code can be made even more
succinct:
a ^= b ^= a ^= b;