Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2<sup>31</sup>, 2<sup>31</sup> - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
<pre>Input: x = 123 Output: 321 </pre>
Example 2:
<pre>Input: x = -123 Output: -321 </pre>
Example 3:
<pre>Input: x = 120 Output: 21 </pre>
Example 4:
<pre>Input: x = 0 Output: 0 </pre>
Constraints:
-2<sup>31</sup> <= x <= 2<sup>31</sup> - 1
题目大意:
反转整数中的数字。
数学法解题思路:
用数学方法每位取余,余数左移。另一种方法是转成字符串然后用字符串反转的方法。
与Java的区别:
- 不需要定义long,因为Python3所有int默认都是long
- 反转str一行完成,非常简洁
注意事项:
- 负值
- 溢出
Python代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14def reverse(self, x: int) -> int:
res, is_negative = 0, False
if x < 0:
is_negative = True
x = -x
while x > 0:
digit = x % 10
res = res * 10 + digit
x //= 10
if res > pow(2, 31) - 1:
return 0
if is_negative:
res = -res
return res
字符串法解题思路:
转为字符串,然后反转。
1
2
3
4
5
6
7
8
9def reverse(self, x: int) -> int:
res, is_negative = 0, False
if x < 0:
is_negative = True
x = -x
res = int(str(x)[::-1])
if res > pow(2, 31) - 1:
return 0
return -res if is_negative else res
算法分析:
- 时间复杂度为
O(n),空间复杂度O(1)。 - 时间复杂度为
O(n),空间复杂度O(n)。


