Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2 Output: 3
Example 2:
Input: a = -2, b = 3 Output: 1
思路: 採用半加法的思想, 即兩個二進制數單獨的位相加其結果可以用異或運算得到,進位可以用與運算得到。
例子2+3,相當於10+11
1.10^11=01,carry=(10&11)<<1=100
2.001^100=101,carry(001&100)<<1=0
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;
}
}
`