gravatar

Blog # 54 : Swapping; Not so easy


Give a method to swap two numbers without using additional memory.



Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Pardon me if I sound frivolous,but if additional memory implies JUST an extra variable,then,the following simple algo can be used:

swap(int a, int b)
{a= b-a;
b= b-a;
a= a+b;
}

gravatar

It can be achieved using XOR operator. To swap a and b we have:
a^=b^=a^=b;

gravatar

@Manoj: You are absolutely right in your words, don't worry :)
@Ankit: You too are correct
There are two methods "using XOR" and "using Addition/Subtraction"

But XOR does not cause overflow, hence it is better :)