Problem
Calculate the sum of two integersaandb, but you arenot allowedto use the operator+and-.
Example:
Givena= 1 andb= 2, return 3.
思路
- Sum of two bits can be obtained by performing XOR (^) of the two bits.
- Carry bit can be obtained by performing AND (&) of two bits.
- keep adding until no carry
public int getSum(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}