LeetCode 371 Sum of Two Intergers

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
按照位把ab相加,不考慮進位,結果是 a xor b(a^b)
計算ab的進位的話,只有二者同爲1才進位,因此進位可以標示爲 (a & b) << 1 ,注意因爲是進位,所以需要向左移動1位

class Solution {
public:
    int getSum(int a, int b) {
        while(b) {
            int c = a & b;
            a = a ^ b;
            b = c << 1;
        }
        return a;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章