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.
因为计算两个数的和又不允许使用+或-操作,可以在二进制下实现这一操作:先用异或计算两个数的二进制相加结果sum,但是不考虑进位情况,然后用与计算得到产生进位的地方,再向左移一位模拟进位carry,(因为两个二进制位包括四种情况,1 1,1 0, 0 0, 0 1,第一种情况相与为1,且正好是产生进位的地方)。然后递归调用函数,直到carry为0,返回sum即可。
if(b==0){
return a;
}
int sum = a^b;
int carry = (a&b)<<1;
return getSum(sum, carry);