Tuesday, May 8, 2018

Swap 2 numbers without using temp variable

Swapping two numbers has been a very common problem in day to day use. Usually people use the approach of a temp variable where they store the value in a temp variable, do the assignment of other variable and restore second variable from temp.

Swap using a temp variable:
swap(int a, int b) {
      int temp = a;
      a = b;
      b = temp;
}

Swap with no temp variable: This approach uses XOR bitwise operation to swap the variables.

swap(int a, int b) {
      a = a ^ b;
      a = a ^ b;
      a = a ^ b; 
}

Swap with no temp variable: This approach uses addition substraction.
swap(int a, int b) {
      a=a+b; //a=15 (5+10)
      b=a-b; //b=5 (15-10)
      a=a-b; //a=10 (15-5)
}

No comments:

Post a Comment

Categories