I read many answers on SO explaining the code using bitwise XOR operator to solve the above problem but none of them seems to explain how to come up with that code.
For example, the following solution uses arithmetic to solve the same problem and I can intuitively think this one.
// C++ Program to swap two numbers without
// using temporary variable
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
cout << "After Swapping: x =" << x << ", y=" << y;
}
Output
After Swapping: x =5, y=10
& The following is the code for solving above problem using XOR
// C++ code to swap using XOR
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 10, y = 5;
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
cout << "After Swapping: x =" << x << ", y=" << y;
return 0;
}
Output:
After Swapping: x =5, y=10
I understand what the above code is doing line by line, but how do I come up with this logic? I had spent hours on this problem in trying to figure out a way to solve it using XOR but couldn't really get it.