题目
Given a 32-bit signed integer, reverse digits of an integer.
Example:
Input: 123,Output: 321
Input: -123,Output: -321
Input: 120,Output: 21
分析
题目中的输入为:一个32位的有符号整数
x
x
.
输出为:倒序的整数。
32位有符号整数的范围是:
−231∼231−1
−
2
31
∼
2
31
−
1
,而由于不同平台(32位和64位系统)之间的差异,其整型范围不同。
我的系统为64位系统,配置的python3也是64位,因此最大范围是
−263∼263−1
−
2
63
∼
2
63
−
1
。
解答
由于python中的取余操作是商向负无穷方向取整,和C语言中的向0方向取整不同。举例来说,对于
m,d
m
,
d
两个整数:
而当 m,d m , d 中有负数时,不同的编程语言采用了不同的方式进行处理,考虑 m=−7 m = − 7 时,
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
remainder = 0
reversed_num = 0
negative_flag = False
maxInt = 2**31 - 1
if x < 0:
negative_flag = True
x = -x
while x > 0:
remainder = x % 10
reversed_num = reversed_num * 10 + remainder
if reversed_num > maxInt:
return 0
x = int(x/10)
if negative_flag is True:
reversed_num = -reversed_num
return reversed_num
当发生溢出时,即倒序的整数大于时,则返回0,最后判断是否添加负数的标记。