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.
解析
这道题是模拟加法器计算两个数的和。
- 个位为
a ^ b
- 进位为
(a & b) << 1
解决
class Solution {
public:
int getSum(int a, int b) {
int result = 0;
while (b != 0) {
result = a ^ b;
b = (a & b) << 1;
a = result;
}
return result;
}
};