A classic problem asked in many interviews and such. And almost every genius will tell you that its simple.
swap(int *x,int *y)
{
*x += *y;
*y = *x - *y;
*x = *x - *y;
}
Simple right? Wrong!
what happens if one value is 2147483647 and the other is 2147483640 ?
You will definitely overflow x and make a mess of it!
So whats the foolproof way? Observe!
swap(int *x, int *y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
So how is it done? Bit-wise Xor operation. Faster, better and guaranteed to get you laid. For more info on bit wise xor Google it or click here
Technorati Tags: C, Variable swap, Bit operations


November 13, 2009 at 5:28 pm
Hey BIT MASTER…i dont see the need for ANDing the mask>>=1 value with -1 in the while loop…can u plz explain?