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;
}
};
解釋:不用加法,用位運算即可算出和,步驟淺顯易懂!