- problem:
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
- tip:
leetcode自己的编译器不能对负数进行左移,也就是最高位符号必须要为0才能左移,所以在a和b相与后,再与上一个最高位为0其他位都为1的数,这样可以强制将最高位清零,然后再进行左移。
- solution:
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);
}
};