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
异或运算(^)是不进位加法,找到进位,将其和异或的结果加起来即可。进位通过与运算(&)并左移一位得到。异或(^)的结果和进位的相加,还是要调用getSum这个函数。代码如下:
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);
}
};
还没有评论,来说两句吧...