Swap Two Numbers
5/7
Swapping is the classic "hold one in your hand" problem. Two values can't occupy one variable, so the usual approach parks one of them in a temporary variable:
int t = a; a = b; b = t;
Two puzzle variants avoid the temporary:
- Arithmetic:
a = a + b; b = a - b; a = a - b;(risks overflow) - XOR:
a ^= b; b ^= a; a ^= b;(fails ifaandbare the same memory location)
Modern languages also offer destructuring: [a, b] = [b, a] in JS and a, b = b, a in Python.