给出两个整数a和b, 求他们的和, 但不能使用 +
等数学运算符。【位运算】
class Solution {
/*
* param a: The first integer
* param b: The second integer
* return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
if (b == 0){
return a;
}
return aplusb(a ^ b , (a & b) << 1);
//用位运算代替加法时 ^表示相加 &表示进位
//二者相加时进位要左移一位,因为进位是跟上一位相加的
//!!!!!!!!注意不要忘记后面的括号!
}
};