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.
不能用+-来实现一个加法运算,我们可以采用位运算。
例如12(1100)+7(0111),可以分解为如下步骤:
1.用^将不用进位的位先算出来,如上述两个数字^后结果为:1011
2.计算进位,因为要进位,所以应当左移一位,1+1才能进位,因此采用&操作,如上述两个数字&并左移动后为:1000
3.不难发现难免还有进位的情况,因此我们要把进位彻底处理完就必须不断左移知道进位为0
AC码如下:
public class Solution {
public int getSum(int a, int b) {
int result = a^b;
int carry = (a&b) <<1;
if(carry!=0) return getSum(result,carry);
return result;
}
}