7.Reverse Integer
题目如下:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
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.
读题之后,知道就是一个整数翻转,区别在于要解决一个内存溢出问题。
首先,看翻转问题,有两种思路:
一、数学方法,也是官方题解推荐的。思路是:对10取余,相加,除10取整。
这种方法思路比较清晰,也利于之后对于溢出的判断。但是问题在于在做取余%运算的时候,Java(官方题解用的Java)和Python的运算规则不同。
Python 模运算 % 向下取整,即 -14 % 10 = -2……6——>-14 % 10 = 6
Java 模运算 % 向上取整,即 -14 % 10 = -1……-4——>-14 % 10 = -4
所以python采用这种方法需要取绝对值再进行翻转。可利用函数:abs()
二、转字符串处理,这种思路官方并不推荐,理由是转换效率低,调用太多库函数。
可能是因为语言特性不同,Python的字符串处理效率反而比方法一的效率高。
并且再考虑到溢出问题,因为判断溢出采用先把 str 转回 int 再判断,如果数字溢出那么在转回 Int 时就已经发生了溢出,因为题目假设的是环境中只能存储32位带符号数,所以应该想办法在转回之前就进行溢出判断。
接下来,看溢出问题,根据不同的翻转思路也有不同的解决思路:
一、同样采用数学方法,也是官方推荐的。思路如下:
溢出条件:大于MAX_VALUE或小于MIN_VALUE。设当前循环的累加结果为 ans ,下一位取余提出的数字为pop。
对于 MAX_VALUE条件,有: ans * 10 + pop > MAX_VALUE
<==>当 ans > MAX_VALUE / 10, 且还存在下一位提取数字 pop 时,溢出。
<==>当 ans == MAX_VALUE / 10, 且 pop > 7 时,一定溢出。
(以上pop>7,推出过程 : MAX_VALUE = 231-1,且由2的幂次归纳可得其个位数只会一次出现 2,4,8,6。所以231个位数为8,那么MAX_VALUE个位数应该为8 - 1 = 7)
对于 MIN_VALUE条件,有:ans * 10 + pop < MIN_VALUE
<==>当 ans < MIN_VALUE / 10, 且还存在下一位提取数字 pop 时,溢出。
<==>当 ans == MIN_VALUE/10, 且 pop < -8 时,溢出。
(以上pop<-8的推导过程同pop>7类似)
这种方法不太适合Python,原因之前提到过,即 % 运算的取整方式不同。
二、对应采用字符串的翻转方法,也可以采用最简单暴力的if判断是否已出。
但唯一的为题就是上面提到过的,如果会溢出,那么在判断前就已经存储了溢出数据。
code1:
1 class Solution: 2 def reverse(self, x: int) -> int: 3 ans = 0 4 5 a = abs(x) 6 while(a != 0): 7 temp = a % 10 8 ans = ans * 10 + temp 9 a = a//10 10 11 if x<0 and ans<=2147483647: 12 return -ans13 elif x>0 and ans<2147483647: 14 return ans 15 else: 16 return 0
这种方法采用数学方法翻转,用的if判断溢出。
code2:
1 class Solution: 2 def reverse(self, x: int) -> int: 3 lst = str(abs(x))[::-1] 4 ans = int(lst) 5 if x < 0 and ans <= 2147483647: 6 return -ans 7 elif x > 0 and ans < 2147483647: 8 return ans 9 else: 10 return 0
这种方法采用字符串转列表进行翻转,最后用if判断溢出。

浙公网安备 33010602011771号