一道有趣的題:計算兩個整數的和(不能使用加減法)——半加法

題目連接code

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

Example 1:leetcode

Input: a = 1, b = 2 Output: 3get

Example 2:io

Input: a = -2, b = 3 Output: 1class

思路: 採用半加法的思想, 即兩個二進制數單獨的位相加其結果能夠用異或運算獲得,進位能夠用與運算獲得。循環

例子2+3,至關於10+11二進制

1.10^11=01,carry=(10&11)<<1=100while

2.001^100=101,carry(001&100)<<1=0co

3.由於carry已經爲0,不產生進位,此時的異或運算即爲加法的結果101

遞歸版本

`
class Solution {

public int getSum(int a, int b) {

    if(b==0)return a;

    int carry=(a&b)<<1;

    int sum=a^b;

    return getSum(sum,carry);

}

}

`

循環版本

`
class Solution {

public int getSum(int a, int b) {

    while (b!=0){

        int carry=(a&b)<<1;

        a=a^b;

        b=carry;

    }

    return a;

}

}

`

相關文章
相關標籤/搜索