Give a method to swap two numbers without using additional memory.
Solution :
- We may use addition/subtraction or XOR to achieve this.
- XOR does not cause overflows and hence is superior.
- Time : O(1)
- Space : O(1)
void swap_xor(int &num1, int &num2){
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
}num2 ^= num1;
num1 ^= num2;
void swap(int &num1, int &num2){
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
num2 = num1 - num2;
num1 = num1 - num2;
No comments:
Post a Comment