Description
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
分析
题目的意思是:给定a和b,求出a+b但是不能用+,-运算符。
- 用与或非运算,这是个递归。
- 例如: 759+674
- 如果我们不考虑进位,可以得到 323
- 如果我们只考虑进位,可以得到 1110
- 我们把上面两个数字加起来 323+1110=1433 就是最终结果了
- 在二进制下来看,不考虑进位的加,0+0=0,0+1=1, 1+0=1,1+1=0,这就是异或的运算规则,如果只考虑进位的加 0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是’与’的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,直接返回第一步的结果。
代码
class Solution {
public:
int getSum(int a, int b) {
if(b==0){
return a;
}
int sum=a^b;
int carry=(a&b)<<1;
return getSum(sum,carry);
}
};
参考文献
[LeetCode] Sum of Two Integers 两数之和