mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
1.0 KiB
1.0 KiB
371. Sum of Two Integers
思路
求两个数的和,要求不能使用操作符+、-。
我们知道计算机底层中的四则运算都是用门电路通过简单的逻辑操作实现的, 例如对于一位的二进制加法:
a | b | sum(和) | cin(进位) |
---|---|---|---|
0 | 0 | 0 | 0 |
0 | 1 | 1 | 0 |
1 | 0 | 1 | 0 |
1 | 1 | 0 | 1 |
所以一位加法规则是: sum = a ^ b, cin = a & b
.
对于多位的加法,我们可以先分别求出sum和cin, 再用sum和左移一位的cin相加求出新的sum和cin, 循环直到cin为0.
C++
class Solution {
public:
int getSum(int a, int b) {
int res = a ^ b, cin = a & b; // 异或操作'^': 相同为0不同为1
while(cin != 0){
a = cin << 1;
b = res;
res = a ^ b;
cin = a & b;
}
return res;
}
};