问题
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.
2.描述
题目很简单,不用加法实现整数相加,对位运算的理解,异或为两个数相加,但是不带进位,与运算为两个数相加的进位,因此只需要进行递归,每次加进位直到进位为0为止。加进位的时候记得将进位向左移一位!!!
3. 代码
public static int getSum(int a, int b) {
while (b != 0){
int jw = a & b; //获得进位
int jfwjw = a ^ b; //获取加法无进位
return getSum(jfwjw,jw << 1); //进位左移一位继续做加法直到进位为0
}
return a;
}