Tuesday, November 1, 2011

Swapping without temporary storage

Give a method to swap two numbers without using additional memory.

Solution :
  1. We may use addition/subtraction or XOR to achieve this.
  2. XOR does not cause overflows and hence is superior.
Complexity :
  • Time : O(1)
  • Space : O(1)
Code :

void swap_xor(int &num1, int &num2){
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
}

void swap(int &num1, int &num2){
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}

No comments:

Post a Comment