mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 371. Sum of Two Integers.md
This commit is contained in:
parent
44ef56affc
commit
f8c808b25f
31
371. Sum of Two Integers.md
Normal file
31
371. Sum of Two Integers.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# [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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user