题意
将数字反过来。没了。
题解
喵蛋为什么要检查数据范围啊!2147483647, 你可知道 Python2 里面 10**100
都是可以直接算的啊!Python2 里面有 sys.maxint
,值是 9223372036854775807
。
输入、输出不合法,都需要返回 0 。实在太坑。
代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
INT_MAX = 0x7fffffff
INT_MIN = (-INT_MAX - 1)
if not INT_MIN < x < INT_MAX:
return 0
minus = 1
ans = 0
if x < 0:
minus = -1
x = abs(x)
while x > 0:
ans = ans * 10 + x % 10
x //= 10
ans *= minus
if not INT_MIN < ans < INT_MAX:
return 0
return ans
运行
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 76 ms
你是 Python
说道 Python 了,发现了一个非常跪的写法:ans = int(('-' if x < 0 else '') + str(abs(x))[::-1])
简单粗暴一句话搞定!充分发挥 Python 的优势!
代码
class Solution(object):
def reverse(self, x):
INT_MAX = 0x7fffffff
INT_MIN = (-INT_MAX - 1)
sign = 1 if x > 0 else -1
ans = sign * int(str(abs(x))[::-1])
return ans if INT_MIN <= ans <= INT_MAX else 0
运行
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 76 ms
桩程序
if __name__ == '__main__':
cases = [
{'x': 123, 'ans': 321},
{'x': -123, 'ans': -321},
{'x': 0, 'ans': 0},
{'x': 100, 'ans': 1},
{'x': -100, 'ans': -1},
{'x': 1534236469, 'ans': 0},
{'x': 2147483647, 'ans': 0},
{'x': -2147483648, 'ans': 0},
{'x': -2147483412, 'ans': -2143847412},
]
for item in cases:
ans = (Solution()).reverse(x=item['x'])
print(str(ans == item['ans']) + "\t=>" + str(ans) + ":" + str(item['ans']))
发表回复