One of the very tricky questions asked in an interview.
Swap the values of two variables like a=10
and b=15
.
Generally to swap two variables values, we need 3rd variable like:
temp=a;
a=b;
b=temp;
Now the requirement is, swap values of two variables without using 3rd variable.
Since the original solution is:
You can make it a two liner by using:
Then make it a one liner by using:
Update: In this we are taking input of two integers from user. Then we are using the bitwise XOR operation to swap them.
Say we have two integers
a=4
andb=9
and then:Let's see a simple c example to swap two numbers without using the third variable.
program 1:
Output:
Before swap a=10 b=20 After swap a=20 b=10
Program 2: Using * and /
Let's see another example to swap two numbers using * and /.
Output:
Before swap a=10 b=20 After swap a=20 b=10
Program 3: Making use of bitwise XOR operator:
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010).
Output:
After Swapping: x = 5, y = 10
Program 4:
No-one has suggested using std::swap, yet.
I don't use any temporary variables and depending on the type of a and b the implementation may have a specialization that doesn't either. The implementation should be written knowing whether a 'trick' is appropriate or not.
Problems with above methods:
1) The multiplication and division based approach doesn’ work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.
2) Both Arithmetic solutions may cause arithmetic overflow. If x and y are too large, addition and multiplication may go out of integer range.
3) When we use pointers to a variable and make a function swap, all of the above methods fail when both pointers point to the same variable. Let’s take a look what will happen in this case if both are pointing to the same variable.
// Bitwise XOR based method
// Arithmetic based method
Let us see the following program.
Output:
After swap(&x, &x): x = 0
Swapping a variable with itself may be needed in many standard algorithms. For example, see this implementation of QuickSort where we may swap a variable with itself. The above problem can be avoided by putting a condition before the swapping.
Output:
After swap(&x, &x): x = 10
Have you looked at XOR swap algorithm?