Write a function to add two integers without using mathematical operators (+, -, *, /).
Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.
Courtesy: Vibhaj
Hints: No hint, think properly. One thing for sure you'll have to use some operators that are not mathematical. Hit again for solution. |
|
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:
1. Time: O(1)
2. 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;
}
|
|
|