题目:
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.
思路:
这是一个半加法的思想,用位操作中的异或和与可以模拟加法,即两个单独的位相加其结果可以用异或得到;进位可以用与操作然后左移得到。这个思想可以推广到两个整数上。我们以1 + 2为例来说明,其二进制表示分别是01和10。异或之后的二进制结果是11,与之后的二进制结果是00,说明不需要进位,那么二进制的11(十进制中的3)就是最终结果了。
以复杂一点的11 + 5为例再说明一下,其二进制分别是1011和0101,异或的结果是1110,这是不考虑进位的时候低四位的情况;它们的按位与结果是0001,说明在最低位上需要进位了,而进位之后的结果是0010,那么此时计算11 + 5就转换为计算1110和0010的和了(即14 + 2)。重复上述过程,直到需要进位的值变为0。那么为什么进位最终一定会变成0呢?读者可以思考一下^_^。
代码:
class Solution {
public:
int getSum(int a, int b) {
while(b) {
int carry = a & b; // the carries in each bit
a = a ^ b; // the new value in each bit
b = (carry << 1); // update the carries
}
return a;
}
};