LeetCode-371. Sum of Two Integers
阿新 • • 發佈:2018-12-25
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.
擴充套件一下,如何不使用+-號實現兩個數相減呢?補碼的減法是將被減數與減數的相反數相加並加一,因此加法可以很容易的被擴充套件成減法。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); }