Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5a52cd9

Browse files
authored
Add a new method for 007_Reverse_Integer.py (qiyuangong#80)
* Add a new method for 007 reverse integer Contributed by @ROMEEZHOU
1 parent 92c80f9 commit 5a52cd9

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

python/007_Reverse_Integer.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,34 @@
11
class Solution:
22
def reverse(self, x):
33
# https://leetcode.com/problems/reverse-integer/
4-
flag = True if x < 0 else False
5-
if flag:
4+
# flag = True if x < 0 else False
5+
# if flag:
6+
# x = -x
7+
# x = str(x)[::-1]
8+
9+
# if flag:
10+
# x = "-" + x
11+
12+
# value = 2 ** 31
13+
# x = int(x)
14+
# if -value <= x < value:
15+
# return x
16+
# return 0
17+
18+
is_neg = False
19+
if x < 0:
620
x = -x
7-
x = str(x)[::-1]
21+
is_neg = True
822

9-
if flag:
10-
x = "-" + x
23+
res = 0
24+
while x > 0:
25+
res *= 10
26+
res += x % 10
27+
x //= 10
28+
if is_neg:
29+
res = -res
1130

12-
value = 2 ** 31
13-
x = int(x)
14-
if -value <= x < value:
15-
return x
16-
return 0
17-
31+
if res < -2**31 or res > 2**31-1:
32+
return 0
33+
return res
34+

0 commit comments

Comments
 (0)