1.题目描述
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.
2.分析
首先想到电路里面加法器的实现:
保留位remain=a^b 0^1=1,1^0=1,0^0=0,1^1=0
进位carry=a&b<<1
3.代码
class Solution {
public:
int getSum(int a, int b) {
int remain = a;
int carry = b;
while (carry) {
int temp = carry^remain;//异或
carry = (carry&remain) << 1;//进位
remain = temp;
}
return remain;
}
};