Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Given a = 1 and b = 2, return 3.
Use XOR and AND to present sum and carry until carry is zero.
-------------------------
| x | y | x ^ y | x & y | carry = x ^ y
-------------------------
| 0 | 0 | 0 | 0 | sum = x & y
-------------------------
| 0 | 1 | 1 | 0 |
-------------------------
| 1 | 0 | 1 | 0 |
-------------------------
| 1 | 1 | 0 | 1 |
-------------------------
class Solution {
public int getSum(int a, int b) {
int carry = (a & b) << 1;
int result = a ^ b;
while (carry != 0) {
int tempCarry = (result & carry) << 1;
result = result ^ carry;
carry = tempCarry;
}
return result;
}
}
class Solution {
public:
int getSum(int a, int b) {
int carry = (a & b) << 1;
int result = a ^ b;
while (carry != 0) {
int tempCarry = (result & carry) << 1;
result = result ^ carry;
carry = tempCarry;
}
return result;
}
};
int getSum(int a, int b) {
int carry = (a & b) << 1;
int result = a ^ b;
while (carry != 0) {
int tempCarry = (result & carry) << 1;
result = result ^ carry;
carry = tempCarry;
}
return result;
}