[LeetCode] Problem 371 - Sum of Two Integers

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

Example

No.1

Input: a = 1, b = 2

Output: 3

No.2

Input: a = -2, b = 3

Output: 1

Code

1
2
3
4
5
6
// 1.不考虑进位的加法就是异或运算;
// 2.只考虑进位就是与运算并左移一位;
// 3.重复前面两步操作直到第二步进位结果为0。
public int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}