KK's blog

每天积累多一些

0%

LeetCode 007 Reverse Integer

LeetCode 007 Reverse Integer

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:

**Input:** x = 123
**Output:** 321

Example 2:

**Input:** x = -123
**Output:** -321

Example 3:

**Input:** x = 120
**Output:** 21

Example 4:

**Input:** x = 0
**Output:** 0

Constraints:

  • -2<sup>31</sup> <= x <= 2<sup>31</sup> - 1

题目大意:

反转整数中的数字。

数学法解题思路:

用数学方法每位取余,余数左移。另一种方法是转成字符串然后用字符串反转的方法。

与Java的区别:

  1. 不需要定义long,因为Python3所有int默认都是long
  2. 反转str一行完成,非常简洁

注意事项:

  1. 负值
  2. 溢出

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def 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
9
def 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

算法分析:

  1. 时间复杂度为O(n),空间复杂度O(1)
  2. 时间复杂度为O(n),空间复杂度O(n)
Free mock interview