Question:
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:
[
−
2
3
1
,
2
3
1
−
1
]
[−2^31, 2^31 − 1]
[−231,231−1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
我的思路:
将x转为字符串,将字符串逆序再转为int即可。
需要考虑的几个点:
- 正负数问题:设置一个符号标记即可
- 正数的范围:必须要限制在32位有符号整数的范围内,即[ − 2 ∗ 31 , 2 3 1 − 1 -2*31,2^31-1 −2∗31,231−1]
- x末尾0的处理:将str转为int时,会默认将前面的0去除掉。如 i n t ( ′ 000012 3 ′ ) int('0000123') int(′0000123′)的结果是123
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >=0 else -1
str1 = str(sign * x)
y = int(str1[::-1]) * sign
return y if -2147483648 < y < 2147483647 else 0
字符串逆序的方式:str1[::-1]表示从头到尾逆序读取
执行内存:40ms,击败60.08%用户
内存消耗:13.5MB,击败5.25%用户
经典思路:
一次次取余,将数字从末尾开始逐步放到高位上。
class Solution:
def reverse(self, x: int) -> int:
y,res = abs(x),0
boundry = 2147483647 if x>0 else 2147483648
while y != 0:
res = res * 10 + y % 10
if res > boundry :
return 0
y //= 10 # python中整除是//
return res if x >0 else -res
执行内存:32ms,击败89.8%用户
内存消耗:13.5MB,击败5.25%用户