Thursday, March 27, 2008

1 + 1 = 3?

Well this was an interesting problem that someone had brought up to me and I felt is merits a post because it is handy if you are ever bound by these strict restrictions ;).

Problem: You have 2 integer variables A and B. You are limited to having only two variables and no more. How would you swap the values of A and B without using a third variable?

Answer: This is the easy part. Someone mentioned this problem to me in passing and I guess it just stuck in my brain. Today while I was working I wasn't even thinking about it and the answer just hit me.

Simple form:

A = A + B
B = A - B
A = A - B

Broken down:

A = A + B
B = (A + B) - B = A
A = (A + B) - B = B

And there we have it ... somewhat useless information that is cool at the same time! =)

No comments: