05 August 2008
Calculate the sum of two integers a and b, but you are not allowed to use the operator
and 1
+
.1
-
Example 1:
1
2
Input: a = 1, b = 2
Output: 3
Example 2:
1
2
Input: a = -2, b = 3
Output: 1
计算两个整数之和,不能用+和-,考察位操作的知识。做法就是, 由“与”a & b可得可以产生进位的地方(二者都为1,结果才为1,两个1相加,进一位); 异或a^b计算无进位的情况,再由(carry = a & b) << 1得到进位后的值(相当于乘以2), 直到进位和为0说明没有进位了,则此时原位和即所求和。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int getSum(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
while (b != 0) {
int carry = a & b; //将存在进位的位置置1
a = a ^ b; // 计算无进位的结果
b = carry << 1;
}
return a;
}
}