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 : http://msdn.microsoft.com/en-us/library/74b4xzyw(v=VS.100).aspx
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!
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 : http://msdn.microsoft.com/en-us/library/74b4xzyw(v=VS.100).aspx
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!
Hi in the first code but you have not included the number or asked the user to input the number.
ReplyDeleteThanks Basarat! There's also the interesting fact that you can solve this by just using the XOR operator as well, which is pretty well explained here too
ReplyDeletehttp://www.programmerinterview.com/index.php/general-miscellaneous/swap-numbers-without-temp/
Nice. I particularly like :
ReplyDeletex = y - x;
y = y - x;
x = x + y;
Which is seems cleaner than the one I presented.