Find a way of swapping two numbers without using temporary variable

This is a brain teaser like question. Assume you have a and b.

a = a+b;
b = a – b; //now b equals the original a.
a = a – b; //now a equals the original b.

You could also use the xor, remember that xor will turn different digits to 1 and same digit to 0

a = a xor b // now record the different bit by marking the corresponding bit 1
b = a xor b // flip the bit in b if corresponding bit in a is 1, keep the same when it is 0 now b equals the original a
a = a xor b // same as the previous step, now a equals to the original b.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s