Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
不用+-法计算两数的和
我们用 & 可以得到二进制位上哪些位置需要进位carry
因为相加进位后该位置为0,所以我们用 ^ 计算两数的值,再将其与carry继续执行该操作,直到carry为0
class Solution {
public:
int getSum(int a, int b) {
while (b) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
};