Skip to content

Commit c8b8724

Browse files
authored
Update 7-Reverse-Integer.py
1 parent 9e01c19 commit c8b8724

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

7-Reverse-Integer.py

+21
Original file line numberDiff line numberDiff line change
@@ -1 +1,22 @@
1+
class Solution:
2+
def reverse(self, x: int) -> int:
3+
# Integer.MAX_VALUE = 2147483647 (end with 7)
4+
# Integer.MIN_VALUE = -2147483648 (end with -8 )
15

6+
MIN = -2147483648 # -2^31,
7+
MAX = 2147483647 # 2^31 - 1
8+
9+
res = 0
10+
while x:
11+
digit = int(math.fmod(x, 10)) # (python dumb) -1 % 10 = 9
12+
x = int(x / 10) # (python dumb) -1 // 10 = -1
13+
14+
if (res > MAX // 10 or
15+
(res == MAX // 10 and digit >= MAX % 10)):
16+
return 0
17+
if (res < MIN // 10 or
18+
(res == MIN // 10 and digit <= MIN % 10)):
19+
return 0
20+
res = (res * 10) + digit
21+
22+
return res

0 commit comments

Comments
 (0)