给一个 32-位有符号整数,将它反转。
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
注意:假设我们处理的环境只能存储32位有符号整数范围内的整数: [−2∧31, 2∧31 − 1]。如果反转后整数溢出,则返回0。
我的方案1:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = x < 0 and -1 or 1
x = flag * x
ret = int(str(x)[::-1]) * flag
if ret > pow(2, 31) - 1 or ret < - pow(2, 31):
return 0
return ret
看了别人的后改进:
def reverse(self, x):
flag = x < 0 and -1 or 1
x = flag * x
ret = int(str(x)[::-1])
return ret*flag if ret < pow(2, 31) else 0
看到评论区比较好的方案:
def reverse(self, x):
s = cmp(x, 0)
r = int(str(s*x)[::-1])
return s*r * (r < 2**31)
更短的:
def reverse(self, x):
s=cmp(x,0);r=int(`s*x`[::-1]);return(r<2**31)*s*r