问题描述:
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.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
大意就是不用+ - 实现两个数字的相加。
不能用加减,想到的就是位运算了。
大意就是不用+ - 实现两个数字的相加。
不能用加减,想到的就是位运算了。
这里用到的就是两个位运算符 异或 ^ 和与&
异或的特点:对应位不同则为1,相同为0
与的特点:都为1则为1
所以与用来保存两个数和的进位。
AC代码如下:
int getSum(int a, int b)
{
if(b == 0)
return a;
int x = a^b;
int y = a&b;
return getSum(x,y<<1);
}