Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 371.sum-of-two-integers.md #405

Merged
merged 1 commit into from
Aug 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions problems/371.sum-of-two-integers.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ Output: 1
- 求与之后左移一位来可以表示进位

## 代码
代码支持:JS,C++,Java,Python
Javascript Code:
```js
/*
* @lc app=leetcode id=371 lang=javascript
Expand All @@ -62,4 +64,60 @@ var getSum = function(a, b) {
return getSum(a ^ b, (a & b) << 1);
};
```
C++ Code:
```c++
class Solution {
public:
int getSum(int a, int b) {
if(a==0) return b;
if(b==0) return a;

while(b!=0)
{
// 防止 AddressSanitizer 对有符号左移的溢出保护处理
auto carry = ((unsigned int ) (a & b))<<1;
// 计算无进位的结果
a = a^b;
//将存在进位的位置置1
b =carry;
}
return a;
}
};
```

Java Code:
```java
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;
// 计算无进位的结果
a = a^b;
//将存在进位的位置置1
b =carry<<1;
}
return a;
}
}
```

Python Code:
```python
# python整数类型为Unifying Long Integers, 即无限长整数类型.
# 模拟 32bit 有符号整型加法
class Solution:
def getSum(self, a: int, b: int) -> int:
a &= 0xFFFFFFFF
b &= 0xFFFFFFFF
while b:
carry = a & b
a ^= b
b = ((carry) << 1) & 0xFFFFFFFF
# print((a, b))
return a if a < 0x80000000 else ~(a^0xFFFFFFFF)
```