题目描述:
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.
题目大意:输出两个数字的和,但不能用+、-号;
思路:做个加法器。
由二进制加法:
a | b | a + b |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 10 |
利用异或(XOR)的性质:相同得0,相异得1。可以得到a + b = a xor b,进位由a和b的与得到(1 & 1 = 1)。加(异或)ab,将进位值加(异或)到结果,再得到新进位值,再加(异或)到结果,直到进位值为0即可。
c++代码:
class Solution {
public:
int getSum(int a, int b) {
while (b)
{
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};