题目描述
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转
假设我们的环境只能存储得下 32 位的有符号整数,反转后溢出返回0
示例
输入: 123
输出: 321
输入: -123
输出: -321
输入: 120
输出: 21
我的解法
import math;
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= (0-math.pow(2, 31)) and x <= (math.pow(2, 31)-1):
if x >= 0:
re_str = str(x)[::-1]
re_num = int(re_str)
else:
re_str = str(x)[1:][::-1]
re_num = 0 - int(re_str)
if re_num >= (0-math.pow(2, 31)) and re_num <= (math.pow(2,31)-1):
return re_num
else:
return 0
else:
return ("Wrong!")
提交结果
题解
考察方法: 弹出和推入数字 & 溢出前进行检查
思路:可以一次构建反转整数的一位数字,可以预先检查向原整数附加另一位数字是否会导致溢出;检查语句溢出