LeetCode/solutions/371. Sum of Two Integers.md

32 lines
1.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [371. Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/description/)
# 思路
求两个数的和,要求不能使用操作符+、-。
我们知道计算机底层中的四则运算都是用门电路通过简单的逻辑操作实现的, 例如对于一位的二进制加法:
| 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++
``` 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;
}
};
```