371. Sum of Two Integers

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1; // 进位部分,即只计算 1&1 这种场景
a ^= b; // 非进位部分相加,1^1 = 0 保证了不重复计算进位部分
b = carry;
}

return a;
}
}

References

371. Sum of Two Integers
剑指 Offer 65. 不用加减乘除做加法
面试题 17.01. 不用加号的加法