[LeetCode]371. Sum of Two Integers

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.

class Solution {
public:
    int getSum(int a, int b) {
         while (b){
            int x = a ^ b;//忽略進位,先將各位相加
            int y = (a & b) << 1;//計算出進位,並將進位左移一位,以便後續相加
            a = x; b = y;//將進位左移的結果和忽略進位的和相加
        }
        return a;
    }
};
發佈了37 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章