Sum of Two Integers【不用+ -,算加法】

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;
    }
};

解釋:不用加法,用位運算即可算出和,步驟淺顯易懂!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章