1
- ### 7. Reverse Integer
1
+ # 7. Reverse Integer 反转整数
2
2
3
- 题目:
4
- < https://leetcode.com/problems/Reverse-Integer/ >
3
+ ## 题目
5
4
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
6
15
7
- 难度:
8
16
9
- Easy
17
+ > 示例 2:
10
18
19
+ 输入: -123
20
+ 输出: -321
11
21
12
- 思路
22
+
23
+ > 示例 3:
24
+
25
+ 输入: 120
26
+ 输出: 21
27
+
28
+ 注意:
29
+ 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。
30
+ 根据这个假设,如果反转后的整数溢出,则返回 0。
31
+ ```
32
+
33
+ ## 难度: Easy
13
34
14
35
翻转数字问题需要注意的就是溢出问题,为什么会存在溢出问题呢,我们知道int型的数值范围是 -2147483648~2147483647(负的2的31次方~ 2的31次方-1), 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,而翻转后的数就超过了范围。
15
36
16
- #### 解法1:
17
- 如果输入的是负数,就递归调用原函数,参数变成-x即可
37
+ > 思路1
18
38
39
+ 如果输入的是负数,就递归调用原函数,参数变成-x即可
19
40
20
41
``` python
21
42
class Solution (object ):
@@ -32,8 +53,11 @@ class Solution(object):
32
53
x /= 10
33
54
return res if res <= 0x 7fffffff else 0
34
55
```
35
- #### 解法2:
56
+
57
+ > 思路2
58
+
36
59
按照参数正负号先将其转成字符串,然后再反转,根据是否溢出决定输出0还是反转结果
60
+
37
61
``` python
38
62
class Solution (object ):
39
63
def reverse (self , x ):
@@ -45,9 +69,10 @@ class Solution(object):
45
69
x = 0 if abs (x) > 0x 7FFFFFFF else x
46
70
return x
47
71
```
48
- #### 解法3(StefanPochmann大神):
49
- 看这个解法前先看[ backticks] ( https://docs.python.org/2.7/reference/expressions.html#string-conversions )
50
72
73
+ > 思路3(StefanPochmann大神):
74
+
75
+ 看这个解法前先看[ backticks] ( https://docs.python.org/2.7/reference/expressions.html#string-conversions )
51
76
52
77
cmp函数在python3.x中用不了了,import operator用gt或者lt吧,或者回归if/else condition爸爸的怀抱吧!
53
78
``` python
@@ -62,4 +87,21 @@ class Solution(object):
62
87
return s * r * (r < 2 ** 31 )
63
88
```
64
89
90
+ > 思路4
91
+
92
+ * 1.记录符号
93
+ * 2.将数字当字符串处理
94
+ * 3.判断是否阈值区间,进行比较就行
65
95
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