Effective way to Swap two numbers using xor

One of the most effective way to swap two numbers is by using XOR gate. We do not any third variable to store value, therefore it has lower space complexity than the traditional swapping program using third or temporary variable.

How it works?

To understand this trick, break the statements into unique values:

x1 = x xor y
y1 = x1 xor y
x2 = x1 xor y1

According to our code, x2 should have y’s original value. Let’s work out the details for the last step:

x2 = x1 xor y1
x2 = x1 xor (x1 xor y)   // replace y1
x2 = (x1 xor x1) xor y   // regroup parenthesis - order does not matter for XOR
x2 = 0 xor y             // a xor a => 0
x2 = y                   // 0 xor a => a; x2 now has y's original value

Now – x2 is equals to y. The swap happened. Now let’s try it out for y1:

y1 = x1 xor y
y1 = (x xor y) xor y
y1 = x xor (y xor y)
y1 = x xor 0
y1 = x                  // y1 == x's original value

Finally y1 is equals to x. Hence the swapping is performed easily without using a temporary variable

CODE:

#include<iostream>
using namespace std;

int main() {
   int num1, num2;

   cout<<"nEnter First Number : ";
   cin>>num1;
   cout<<"nEnter Second Number : ";
   cin>>num2;


   num1 = num1 ^ num2;
   num2 = num1 ^ num2;
   num1 = num1 ^ num2;

   cout<<"n Numbers after Swapping : ";
   cout<<"n Num1 = "<<num1;
   cout<<" and Num2 = "<<num2;

   return(0);
}

OUTPUT:

Enter First Number : 13

Enter Second Number : 7

 Numbers after Swapping :
 Num1 = 7 and Num2 = 13
--------------------------------
Process exited after 3.041 seconds with return value 0
Press any key to continue . . .

4 thoughts on “Effective way to Swap two numbers using xor”

  1. This fails completely to work if num1 == num2.

    It’s also slower than using a temporary variable and fragile since it will produce undefined behaviour if not used on integers.

    Why can’t you use a temporary variable? It’s faster and more reliable.

    Reply
  2. This is a kind of neat trick to know about, but there’s nothing particularly ‘effective’ about it. It tends to perform poorly on modern hardware and it’s less readable than ‘swap(num1, num2)`.

    Reply

Leave a Comment