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;
-
- }
}
`