Popular Posts

Sunday, July 24, 2011

Swap two variables without using temporary variable

Swap x and y without using temp variable
tmp = x
x = y
y = tmp
-----------------
x=x+y
y=x-y
x=x-y
Drawbacks : 
1) It can cause overflow in the operation (+
) 
                     2) It can cause underflow on operation (-)
----------------- x=x*y y=x/y x=x/y
----------------------
x = x xor y
y = x xor y
x = x xor y
We don't have problem of either underflow or overflow! but it fails for swapping of same value results 0.

No comments:

Post a Comment