Description
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.
Thinking Process
- At each iteration, calculate the carry bits and the addition result(with no carry) separately
- At next iteration, shift the carry result from last iteration left by 1 and add it to the addition result
public int getSum(int a, int b) {
//store result in a, store carry in b
while(b != 0){
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}