题目:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
这道题要求不能用加法和减法,那么就只能使用位运算来做了。
class Solution {
public:
int add(int a, int b){
if(b == 0)
return a;
int sum = a ^ b;
int car = ((unsigned int)a & (unsigned int)b) << 1;
return add(sum, car);
}
int getSum(int a, int b) {
return add(a, b);
}
};