Description
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
Solving
Seperating the operation into two parts: manipulating numbers without carry named half; carry numbers named carry. So we can turn the orignal problem into a while-loop which get both half and carry util all the carry numbers become 0. At first, we can see two parameters as half and carry. Using XOR to get half and AND to get carry.
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int half = a ^ b;
int carry = (a & b) << 1;
a = half; b = carry;
}
return a;
}
}