题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1
输入: 123
输出: 321
示例 2
输入: -123
输出: -321
示例 3
输入: 120
输出: 21
注意
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
第一次代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
LessThanZero = False
if x < 0:
LessThanZero = True
x = abs(x)
num = []
flag = True
while x > 0:
number = x % 10
if flag and number == 0:
x //= 10
continue
if number != 0:
flag = False
num.append(number)
x //= 10
#num.append(x)
k = len(num) - 1
aim = 0
for i in num:
#print(i)
aim += i * 10 ** k
k -= 1
if LessThanZero:
aim *= -1
if (aim >= -2 ** 31) and aim <= (2 ** 31 - 1):
return aim
return 0
思路就是不停的取余。第一遍代码使用了列表存放反转的数,其实是很没有必要,这样还得判断0是不是在最高位。结果在取余的循环里直接计算即可。改进后的代码如下,时间还是36ms:
第二次代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
LessThanZero = False
if x < 0:
LessThanZero = True
x = abs(x)
aim = 0
while x > 0:
number = x % 10
aim = aim * 10 + number
x //= 10
if LessThanZero:
aim *= -1
if (aim >= -2 ** 31) and aim <= (2 ** 31 - 1):
return aim
return 0
最后在评论里学到的解法,将数字转换为字符串处理,时间40ms代码如下:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
x = -int(str(-x)[::-1])
else:
x = int(str(x)[::-1])
if (x >= -2 ** 31) and x <= (2 ** 31 - 1):
return x
return 0