PROBLEM:
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
SOLVE:
class Solution {
public:
int getSum(int a, int b) {
long long sum=a;
while(b!=0){
// 每一位有1+1、0+1、0+0地中情况,不考虑进位
// 本位上1+1->0(进1但本位不体现)、0+1->1、0+0->0
// 可见与 ^ 的运算结果一致
sum=a^b;
// b 就代表进位的数值
b=(a&b)<<1;
// a 就代表上一步计算出本位的和
a=sum;
}
return sum;
}
};
解释:不用加法,用位运算即可算出和,步骤浅显易懂!