Labels

Tuesday, February 17, 2015

Swap Two Numbers Without Temp

How to swap two numbers without a third variable?

I just collected two ways:

1. use bit operation:

a = a ^ b;
b = a ^ b;
a = a ^ b;

to illustrate:
b = (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a
a = a ^ b ^ (a ^ b ^ b) = a ^ b ^ a = a ^ a ^ b = 0 ^ b = b;



2. use -/+

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

To illustrate:
b = a+b-b = a;
a = a+b-(a+b-b)=b;

No comments:

Post a Comment