不使用运算符 +
和 -
,计算两整数 a
、b
之和。
输入: a = 1, b = 2
输出: 3
输入: a = -2, b = 3
输出: 1
let getSum = (a, b) => {
return b === 0 ? a : getSum((a ^ b), (a & b) << 1);
};
console.log(getSum(1, 2));
console.log(getSum(-2, 3));
func getSum(a int, b int) int {
if b == 0 {
return a
} else {
return getSum(a ^ b, (a & b) << 1)
}
}
class Solution {
public int getSum(int a, int b) {
return b == 0 ? a : getSum((a ^ b), (a & b) << 1);
}
}