swapping of two numbers in one line
Posted by pankaj4u4m on August 12, 2009
Today when i was programming I saw one interesting thing, swapping of two numbers in one line!!!!
Previously I know how to swap two numbers usins bitwise operator but this is simple using ordinary operation…:)
here is using bitwise operator.
1.For first expression if we seperate the expression it will like this-
First a=a+b will evaluate thusand then if we subtract b from a now it will give the original value of a and is assigned to b. So now b contain the value of a. In next after assigning a to b again subtract b from a i.e this time it will give the original value of b and is assigned to a. So the result is a contain the valuse of b and b contain the value of a i.e swapped.
b=a-b =>5-2 =>b=3 (original value of a)
a=a-b =>5-3 =>a=2(original value of b)
2. For second expression:
lets understand with an example. a=3 ,b=2;
if we convert it into binary form a=11,b=10;
so in first step a=a^b => 11(XOR)10 =>01(now value of a)
in next b=b^a => 10(XOR)01 => 11(now value of b and original value of a)
next a=a^b => 01(XOR)11 => 10 (now value of a original value of b)
so it is swapped.