题目
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位的有符号整数xx.
输出为:倒序的整数。
32位有符号整数的范围是:−231∼231−1−231∼231−1,而由于不同平台(32位和64位系统)之间的差异,其整型范围不同。
我的系统为64位系统,配置的python3也是64位,因此最大范围是−263∼263−1−263∼263−1。
解答
由于python中的取余操作是商向负无穷方向取整,和C语言中的向0方向取整不同。举例来说,对于m,dm,d 两个整数:
q=m/dr=m%dq=m/dr=m%d
其满足的条件为m=q×d+rm=q×d+r,因此不限制rr的正负时,其实有两种选择, 比如: 7=1×10+(−3)7=0×10+77=1×10+(−3)7=0×10+7
但现实生活中,我们常默认余数是正数,因此选择余数r=7r=7。 而当m,dm,d 中有负数时,不同的编程语言采用了不同的方式进行处理,考虑m=−7m=−7时,
−7=−1×10+(3)(1)(1)−7=−1×10+(3)
7=0×10+(−7)(2)(2)7=0×10+(−7)
(1)(1)中的商为-1,而(2)(2)式中的商为0,前者被称为商向负无穷方向取整,而后者则为商向0方向取整。为了简便起见,我们首先判断输入的xx是否为负数。代码如下:
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,最后判断是否添加负数的标记。