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.
class Solution {
public:
int getSum(int a, int b) {
//将十机制加法转化为二进制加法
//非进位项用异或获得,进位项用与获得,进位项向左移位获得真正的进位数
//重复这个操作直到不能再进位
if(b == 0) return a;
int nocarrynum = a ^ b;
int carrynum = (a & b)<<1;
return getSum(nocarrynum, carrynum);
}
};