Tuesday, November 1, 2011

Tricky addition

Write a function to add to integers without using mathematical operators (+, -, *, /, ^).

Solution :
We use the logic used in digital circuits where sum = A XOR B and carry = A AND B. We simply add the carry again after shifting it 1 left till it become zero.
Complexity :
  • Time : O(1)
  • Space : O(1)
Code :

int add(int a, int b){
int carry = 0;
while(b){
carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}

No comments:

Post a Comment