Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

在不考虑进位的情况下 a ^ b,只考虑进位的情况下 (a & b) << 1,这两个结果相加为和的结果

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int getSum(int a, int b) {
int sum = a ^ b;
int extra = (a & b) << 1;

if (extra != 0)
return getSum(sum, extra);

return sum;
}
};