Skip to content

Commit 811aa86

Browse files
添加: 7. Reverse Integer 反转整数 思路4
1 parent aad4e44 commit 811aa86

File tree

1 file changed

+53
-11
lines changed

1 file changed

+53
-11
lines changed

docs/Leetcode_Solutions/007._Reverse_Integer.md

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,42 @@
1-
### 7. Reverse Integer
1+
# 7. Reverse Integer 反转整数
22

3-
题目:
4-
<https://leetcode.com/problems/Reverse-Integer/>
3+
## 题目
54

5+
* https://leetcode.com/problems/Reverse-Integer
6+
* https://leetcode-cn.com/problems/reverse-integer/description/
7+
8+
```
9+
给定一个 32 位有符号整数,将整数中的数字进行反转。
10+
11+
> 示例 1:
12+
13+
输入: 123
14+
输出: 321
615
7-
难度:
816
9-
Easy
17+
> 示例 2:
1018
19+
输入: -123
20+
输出: -321
1121
12-
思路
22+
23+
> 示例 3:
24+
25+
输入: 120
26+
输出: 21
27+
28+
注意:
29+
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。
30+
根据这个假设,如果反转后的整数溢出,则返回 0。
31+
```
32+
33+
## 难度: Easy
1334

1435
翻转数字问题需要注意的就是溢出问题,为什么会存在溢出问题呢,我们知道int型的数值范围是 -2147483648~2147483647(负的2的31次方~2的31次方-1), 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,而翻转后的数就超过了范围。
1536

16-
#### 解法1:
17-
如果输入的是负数,就递归调用原函数,参数变成-x即可
37+
> 思路1
1838
39+
如果输入的是负数,就递归调用原函数,参数变成-x即可
1940

2041
```python
2142
class Solution(object):
@@ -32,8 +53,11 @@ class Solution(object):
3253
x /= 10
3354
return res if res <= 0x7fffffff else 0
3455
```
35-
#### 解法2:
56+
57+
> 思路2
58+
3659
按照参数正负号先将其转成字符串,然后再反转,根据是否溢出决定输出0还是反转结果
60+
3761
```python
3862
class Solution(object):
3963
def reverse(self, x):
@@ -45,9 +69,10 @@ class Solution(object):
4569
       x = 0 if abs(x) > 0x7FFFFFFF else x
4670
return x
4771
```
48-
#### 解法3(StefanPochmann大神):
49-
看这个解法前先看[backticks](https://docs.python.org/2.7/reference/expressions.html#string-conversions)
5072

73+
> 思路3(StefanPochmann大神):
74+
75+
看这个解法前先看[backticks](https://docs.python.org/2.7/reference/expressions.html#string-conversions)
5176

5277
cmp函数在python3.x中用不了了,import operator用gt或者lt吧,或者回归if/else condition爸爸的怀抱吧!
5378
```python
@@ -62,4 +87,21 @@ class Solution(object):
6287
return s * r * (r < 2 ** 31)
6388
```
6489

90+
> 思路4
91+
92+
* 1.记录符号
93+
* 2.将数字当字符串处理
94+
* 3.判断是否阈值区间,进行比较就行
6595

96+
```python
97+
class Solution:
98+
def reverse(self, x):
99+
"""
100+
:type x: int
101+
:rtype: int
102+
"""
103+
mark = 1 if x>=0 else -1
104+
x_abs = abs(x)
105+
result = mark * int(''.join(str(x_abs)[::-1]))
106+
return result if -2**31 <= result <= 2**31-1 else 0
107+
```

0 commit comments

Comments
 (0)