一. 题目
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.
二. 思路
题目为计算两个整数的和,并且要求不能使用+和-。
整数运算的底层运算也是用位运算完成的,而加法可以用二进制数的异或和进位来共同表示。两个二进制数异或相当于是不进位的加法,所以对两个数进行异或操作后再进位即可。当两数的对应位数都为1时需要进1位(移位运算符<<),则进位操作位(数1 & 数2)<<1。
三. AC代码
public int getSum(int a, int b) {
int temp1=a^b;
int temp2=(a&b)<<1;
if(temp2!=0)
return getSum(temp1,temp2);
return temp1;
}