Thursday, January 10, 2008

Swapping 2 numbers without using one more variable

int a = 7;
int b = 8;
b = a + b; // 7 + 8 = 15
a = b - a; // 15 - 7 = 8
b = b - a; // 15 - 8 = 7

It can be used for other basic datatypes like char, double, float, long.
This solution however has the problem of overflow/underflow, so does

a = a * b;
b = a / b;
a = a / b;

For variables of same size XORing provides better solution.
a = a ^ b;
b = a ^ b;
a = a ^ b;


Complexity: SIMPLE.

No comments: