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 = a^b + (a&b)<<1,用递归的方法求和即可。
代码:
class Solution {
public:
int getSum(int a, int b)
{
int tmp=a;
a=a^b;
b=(tmp&b)<<1;
while(b)
{
tmp=a;
a=a^b;
b=(tmp&b)<<1;
}
return a;
}
};