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.
不使用+-等运算符计算a和b的和
算法分析
假设a与b相加
- 不考虑进位:
a^b为a与b中数字相加的和 - 考虑进位:
a&b<<1为a与b相加应有的进位 -
a+b可以转换为a^b + a&b<<1 -
a&b为0时,a^b为要求的和
Java代码
public class Solution {
public int getSum(int a, int b) {
int x = a & b;//相加后的进位
int y = a ^ b;//相加后的数字和
if (x == 0) return y;
else return getSum(x<<1, y);
}
}
