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
参考资料:here。
这道题需要注意的点是当输入有负数时,无法对【int】类型的数据使用左移运算,因此a&b的结果应该用【unsigned int】保存。
class Solution {
public:
int getSum(int a, int b) {
while (b) {
unsigned int c = a & b;
a = a ^ b;
b = c << 1;
}
return a;
}
};