Saturday, March 26, 2011

Swap two numbers without using a temp variable

A friend of mine asked this question while we were in college. I didn't pay much attention to the question, didn't believe it was possible (because we were taught how to swap variables ... and taught to use a temp variable for it). I thought he joking and moved on.

But in my first programming job test this question was there: "How can you swap two numbers without using a temp variable. Hint: think of a mathematical operator"
And the hint gave it away :) I was quite proud of figuring it out myself. You basically just need to store the sum and subtract alternately. Here .. look at the code :

Some C#ish notes: 
Notice that it works even beyond int.MaxValue :) But for it to work you need to make sure that the assembly is not built with checked option and the code is not in a checked scope :

And Just out of curiosity:
Know that in python being a super cool language you can just do :
[x , y] = [ y , x ]

Now ain't that super cool!

Live and learn....and Enjoy!