一.问题描述
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
二.解题思路
这道题主要还是对数值溢出的处理,因为python本身对整型长度没有定位,所以对python来说就很容易,直接反转过来然后判断这个数是否大于2^31-1就好,但是对于像C++这样的语言来首,不能在没有判断是否溢出之前直接就转换过来,不然直接报错溢出(当然你要是用的long型就不会出这个问题)。下面方法当时假装我们python整型有位数限制,最大就是32位。
2^31-1=2147483647
如何在不把反转的数转化过来之前判断,我们可以这样,
1.当处理的数字的前9位时,判断前9位是否>214748364,如果大于这个数了并且有第十位,那么肯定是溢出的,
2.如果等于这个数并且第十位大于7,那么也是溢出。
3.然后如果前十位小于2147483647但是有第十一位,那么肯定也是溢出。
其实第三种在实现中的时候可以并到第一种,即第三种的前10位是小于上限的,但是如果后面还有位数,它的前十位会去和上限的前9位进行比较,明显大于,因此是溢出的,具体可以去看一下方法一的代码。
实现的方法主要有两种
方法一:连除和连乘
每次通过求余获得x的最后一位的值,然后保存结果的变量乘10并加上x的最后一位的值,一直持续直到x变为0为止。
当然中间得加上溢出判断机制。
方法二:转换成字符串反转
这个就没啥好说了,主要就是注意一下符号的处理和溢出的判断。
更多leetcode算法题解法: 专栏 leetcode算法从零到结束 或者 leetcode 解题目录 Python3 一步一步持续更新~
三.源码
方法一:
class Solution:
def reverse(self, x: int) -> int:
maximum,negative,rst=2**31-1,False,0
temp1,temp2=maximum%10,maximum//10
if x<=0:
negative=True
x=-x
while x:
temp=x%10
# this if statement can merge case 1 and case 3 to detect overflow
if rst>temp2 or rst==temp2 and temp>temp1:
return 0
rst=rst*10+temp
x//=10
return -rst if negative else rst
方法二:
class Solution:
def reverse(self, x: int) -> int:
maximum,sign,rst=2**31-1,1,0
temp1,temp2=maximum%10,maximum//10
if x<=0:sign=-1
x=sign*x
str_x=str(x)
n,str_x=len(str_x),str_x[::-1]
if n>10:return 0
elif n==10:
f_9bit,last_bit=int(str_x[:9]),int(str_x[-1])
print(f_9bit,last_bit)
if f_9bit>temp2 or f_9bit==temp2 and last_bit>temp1:return 0
rst=f_9bit*10+last_bit
else:rst=int(str_x)
return sign*rst