sum of two integers


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.


Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class {
public int getSum(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return 0;
while(b != 0) {
int c = a & b;
a = a ^ b;
b = c << 1;
}
return a;
}
}

求减法只需将改变 c = (~a) & b