forked from algorhythms/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path007 Reverse Integer.py
More file actions
38 lines (30 loc) · 852 Bytes
/
007 Reverse Integer.py
File metadata and controls
38 lines (30 loc) · 852 Bytes
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
"""
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
"""
__author__ = 'Danyang'
class Solution(object):
def reverse(self, x):
"""
Sign for preserving negative number of positive number
:param x: int
:return: int
"""
sign = -1 if x < 0 else 1 # preserve the sign first
x *= sign
# eliminated leading zero in the reversed integer
while x:
if x%10 == 0:
x /= 10
else:
break
# string manipulation
x = str(x)
lst = list(x) # list('123') returns ['1', '2', '3']
lst.reverse()
x = "".join(lst)
x = int(x)
return sign*x
if __name__ == "__main__":
print Solution().reverse(123)