1. 程式人生 > >LeetCode-371. Sum of Two Integers

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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

由於不能使用+和-號,我們迴歸到計算機最基礎的操作位運算上。計算機上以補碼的形式儲存數字,補碼的加法與基礎加法一致。 回想一下基礎加法的過程,首先是將所有位數相加1+0=0,0+1=1,0+0=0 ,1+1=0(並進位),再將進位部分提到上一位數字相加。 因此,相加的結果對應異或的結果,進位的結果對應與的結果(只有加數都是1才能需要進位),因為要與上一位數字相加,因此要講加數想與的結果往左移一位。

class Solution {
    public int getSum(int a, int b) {
        if(b==0)return a;
    	int tmp1=a^b;
    	int tmp2=(a&b)<<1;
    	return getSum(tmp1,tmp2);        
    }
}
擴充套件一下,如何不使用+-號實現兩個數相減呢?補碼的減法是將被減數與減數的相反數相加並加一,因此加法可以很容易的被擴充套件成減法。

    public int getSubtract(int a, int b) {
        /*if(b==0)return a;
    	int tmp1=a^b;
    	int tmp2=((~a)&b)<<1;
    	return getSubtract(tmp1,tmp2);*/
    	 if(b==0)return a;
    	 return getSum(getSum(a,~b),1);
    }