Saturday, April 09, 2011

Swapping to numbers without an auxiliary variable

Hi,

following with my current geek/nerd stuff writing spree, today I want to introduce a very simple way to swap to numbers, without a third variable

a = a + b
b = a - b
a = a - b

Nice and simple, the explanation is dead simple and obvious, but anyway here it goes:

a = a + b , nothing to say here
b = a - b = a + b - b = a
a = a - b = a + b - a = b

There is another nice, yet less intuitive way to do this, by using XOR:

a = a XOR b
b = a XOR b
a = a XOR b

Think about it, and enjoy.