close

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

題意

  算出兩數的和,但不允許使用運算子+。

想法

  原先毫無想法,想想加法器的原理,應該是要用邏輯運算符號,如果用xor可以得到兩數相加,不考慮進位;如果用and可以得到兩數進位的位置,再左移後,並與剛剛的相加,即是結果。

流程

  1. xor

  2. and then shift left 1 bit

  3. xor + and

  4. 檢查 and 結果是不是 0,不是就重複 1~3 步驟

int getSum(int a, int b) {
    if (b == 0)
        return a;
    else{
        return getSum(a^b, (a&b)<<1);
    }
}
 

arrow
arrow
    文章標籤
    LeetCode
    全站熱搜
    創作者介紹
    創作者 Davis 的頭像
    Davis

    Epoch

    Davis 發表在 痞客邦 留言(0) 人氣()