Search This Blog

Tuesday, June 21, 2011

Swap 2 integers without using a temp variable

There are 2 ways to do it. 
  1. use sum of the 2 variables:
 void swap(int a, int b) {
       a = a + b;
       b = a - b;
       a = a - b
    }

     2. use bitwise operation (xor)
void swap(int a, int b) {
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
    }

No comments:

Post a Comment