思路
转换为字符串,再转换为列表,分类讨论非负数、负数,然后翻转
代码实现
class Solution:
def reverse(self, x: int) -> int:
tmp = list(str(x))
if tmp[0] != '-':
result_list = tmp[::-1] #翻转列表
tmp_str = ''.join(result_list) #列表转换为字符串
if (int(tmp_str))<2**31-1:
return int(tmp_str)
else:
return 0
else:
del tmp[0]
result_list = tmp[::-1]
tmp_str = ''.join(result_list)
if (-int(tmp_str))>-2**31:
return -int(tmp_str)
else:
return 0
执行结果
执行用时 : 40 ms, 在Reverse Integer的Python3提交中击败了99.88% 的用户
内存消耗 : 13.1 MB, 在Reverse Integer的Python3提交中击败了94.93% 的用户