Given two numbers, Swap those two numbers without using temporary variable.
The Challenge
In the previous question (#24), we used a temporary variable. But what if we told you there are clever mathematical and bitwise tricks to swap without using extra memory? Welcome to the world of space-efficient algorithms!
long long a = 23, b = 26;
a = a ^ b; // Step 1: a = 23 ^ 26 = 13
b = a ^ b; // Step 2: b = 13 ^ 26 = 23 (original a!)
a = a ^ b; // Step 3: a = 13 ^ 23 = 26 (original b!)
// Result: a=26, b=23 ✓ Swapped!
What is XOR (Exclusive OR)?
XOR returns 1 when bits are different, 0 when they're the same:
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
// Example with numbers:
23 in binary: 10111
26 in binary: 11010
-----
23 ^ 26 : 01101 = 13
// Key Properties of XOR:
// 1. a ^ a = 0 (same number cancels out)
// 2. a ^ 0 = a (XOR with 0 keeps the number)
// 3. a ^ b ^ b = a (b cancels itself)
// Starting values: a=23, b=26
// Step 1: a = a ^ b
a = 23 ^ 26 // a now holds (23 ^ 26)
// Step 2: b = a ^ b = (23 ^ 26) ^ 26
// = 23 ^ (26 ^ 26)
// = 23 ^ 0
// = 23 ✓ (original a!)
// Step 3: a = a ^ b = (23 ^ 26) ^ 23
// = (23 ^ 23) ^ 26
// = 0 ^ 26
// = 26 ✓ (original b!)
long long a = 23, b = 26;
a = a + b; // a = 23 + 26 = 49
b = a - b; // b = 49 - 26 = 23 (original a!)
a = a - b; // a = 49 - 23 = 26 (original b!)
// Result: a=26, b=23 ✓ Swapped!
a + b
exceeds the maximum value of
the data type (e.g., INT_MAX), the result wraps around and corrupts the values.
XOR doesn't have this problem!
long long a = 23, b = 26;
a = a * b; // a = 23 * 26 = 598
b = a / b; // b = 598 / 26 = 23 (original a!)
a = a / b; // a = 598 / 23 = 26 (original b!)
// Result: a=26, b=23 ✓ Swapped!
Method | Extra Space | Overflow Risk | Works with 0 | Readability | Best For |
---|---|---|---|---|---|
Temp Variable | ❌ Needs temp | ✅ No risk | ✅ Yes | ⭐⭐⭐⭐⭐ | General use |
XOR Bitwise | ✅ No extra | ✅ No risk | ✅ Yes | ⭐⭐⭐ | Integers only |
Arithmetic (+/-) | ✅ No extra | ⚠️ Possible | ✅ Yes | ⭐⭐⭐⭐ | Small numbers |
Multiply/Divide | ✅ No extra | ⚠️ High risk | ❌ Fails! | ⭐⭐ | Rarely used |
XOR isn't just for swapping - it's used in:
// Array has numbers 1-5, but one is missing
int arr[] = {1, 2, 4, 5}; // 3 is missing
int xor_all = 1 ^ 2 ^ 3 ^ 4 ^ 5; // XOR of complete set
int xor_arr = 1 ^ 2 ^ 4 ^ 5; // XOR of array
int missing = xor_all ^ xor_arr; // Result: 3!
Mastering XOR opens doors to elegant solutions for complex problems!
#include <iostream>
using namespace std;
int main() {
long long a, b;
cin >> a >> b;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "num1=" << a << "\nnum2=" << b;
return 0;
}