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)
int add(int a, int b){
int carry = 0;
while(b){
return a;
}while(b){
carry = a & b;
a = a ^ b;
b = carry << 1;
}a = a ^ b;
b = carry << 1;
return a;
No comments:
Post a Comment