## Sunday, June 17, 2018

### Swap Two Integers without using a Temporary Variable

This is an older exercise, but it still comes up.
This falls under things you wouldn't bother worrying about in real life.

## Swap Two Integers without using a Temporary Variable

The idea is to just add the two integer variables and then subtract each piece out in turn.

Say you have x=5 and y=9.

If you are using Python you can just stop right here as "tuple unpacking" will so all the work for you.

x, y = (y, x)

and you are done. x is 9 and y is 5.

Let's assume you want to do it the harder way...

Replace x with the sum of x and y.

x = x + y

x = 5 + 9 = 14

Now you have "lost" x, but you still have y and you can deduce what your old x is.

For the new y take your total and subtract out y, which will leave you with the "old" x in y's place.

y = x - y

y = 14 - 9 = 5

Now to get the new x, take the total and subtract out the new y. which will give you the old y which goes in x's place.  It's more confusing to write it out in English that to just see the math.

x = x - y

x = 14 - 5 = 9

To Summarize

x = x + y   [x changes]
y = x - y    [y changes: Total minus original y]
x = x - y    [x changes again]