# 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 1:

``````Input: a = 1, b = 2
Output: 3
``````

Example 2:

``````Input: a = -2, b = 3
Output: 1
``````

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

1. 如果不考虑进位，可以得到 323

2. 如果只考虑进位，可以得到 1110

3. 把上面两个数字假期 323+1110=1433 就是最终结果了

runtime error: left shift of negative value -2147483648，对INT_MIN左移位。

``````class Solution {
public:
int getSum(int a, int b) {
if (b == 0) return a;
int sum = a ^ b;
int carry = (a & b & 0x7fffffff) << 1;
return getSum(sum, carry);
}
};
``````

``````class Solution {
public:
int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b & 0x7fffffff) << 1);
}
};
``````

``````class Solution {
public:
int getSum(int a, int b) {
while (b) {
int carry = (a & b & 0x7fffffff) << 1;
a = a ^ b;
b = carry;
}
return a;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/371

https://leetcode.com/problems/sum-of-two-integers/

https://leetcode.com/problems/sum-of-two-integers/discuss/84290/Java-simple-easy-understand-solution-with-explanation

https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation