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
思路:用XOR来进行加计算,类似: 1+2 = 0001 + 0010 = 0011 = 3,
进位,用&<<1来算,例如: 1+1 = 0001 & 0001 = 0001 <<1 = 0010 = 2.
然后,tricky的地方在于 while循环是用b来判断是否为0,而且carry用来保存中间值,以确保原来的a,b不受影响。
public class Solution {
public int getSum(int a, int b) {
while(b != 0) {
int carry = (a & b ) <<1;
a = a ^ b;
b = carry;
}
return a;
}
}