-
Notifications
You must be signed in to change notification settings - Fork 0
/
alg007_reverse_integer.py
57 lines (49 loc) · 1.42 KB
/
alg007_reverse_integer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 7. Reverse Integer (Medium)
# https://leetcode.com/problems/reverse-integer/
#
# Given a 32-bit signed integer, reverse digits of an integer.
# Assume we are dealing with an environment which could only store integers within
# the 32-bit signed integer range: [−231, 231 − 1].
# For the purpose of this problem, assume that your function returns 0
# when the reversed integer overflows.
#
# Examples:
# Input: 123
# Output: 321
#
# Input: -123
# Output: -321
#
# Input: 120
# Output: 21
class Solution:
def reverse(self, x):
digits = []
if x < 0:
neg = -1
x = -x
else:
neg = +1
dv = 10
while x > 0:
digits.append(x % dv)
x = x // dv
# print(digits)
y = 0
dv = 1
for i in range(len(digits) - 1, -1, -1):
# print(y)
if -1 * 2 ** 31 <= neg * (y + dv * digits[i]) <= 2 ** 31 - 1:
y += dv * digits[i]
dv *= 10
else:
y = 0
break
y = neg * y
return y
# ===============================================================================
# ===============================================================================
# ===============================================================================
if __name__ == "__main__":
sol = Solution()
print(sol.reverse(-123))