LeetCode07--整数反转

 1 '''
 2 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
 3  示例 1: 输入: 123 输出: 321
 4  示例 2: 输入: -123 输出: -321
 5  示例 3: 输入: 120 输出: 21
 6 '''
 7 
 8 
 9 class Solution:
10     def reverse(self, x):
11         """
12         :type x: int
13         :rtype: int
14         """
15         f = False
16         x_s = list(str(x))
17         if x_s[0] == '0':
18             return ''
19         if x_s[0] == '-':
20             f = True
21             del x_s[0]
22         if x_s[-1] == '0':
23             del x_s[-1]
24 
25         xl = reversed(x_s)
26         xs = ''.join(xl)
27         if f:
28             return int('-'+xs) if int(xs) < 2 **31 -1 else 0
29         else:
30             return int(xs) if int(xs) < 2 **31 -1 else 0
31 
32 
33 if __name__ == '__main__':
34     x = -6744670
35     ret = Solution().reverse(x)
36     print(ret)

 

posted @ 2018-12-03 14:47  浅尝辄止易初心不改难  Views(156)  Comments(0Edit  收藏  举报