反转整数

反转整数

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2**31,  2**31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

 1 class Solution:
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         y = 0
 8         flag = 0
 9         if x < 0:
10             x = -1 * x
11             flag = 1
12         while x/10:
13             y = y*10 + x%10
14             x = x//10
15         if flag == 1:
16             y = -1*y
17         if y < pow(-2, 31) or y > pow(2, 31) - 1:
18             return 0
19         return y

代码简化:

 1 class Solution:
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         res = int(str(x)[::-1]) if x > 0 else -int(str(x).lstrip('-')[::-1])
 8         return res if -2 ** 31 <= res <= 2 ** 31-1 else 0

 

1.  lstrip()

Python lstrip() 方法用于截掉字符串左边的空格或指定字符。

2.  [::-1]

用于取反向字符串

3.  注意if else 的结构

posted @ 2018-07-10 21:34  卉卉卉大爷  阅读(169)  评论(0编辑  收藏  举报