7. Reverse Integer

2019-03-28

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

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.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
"""
if x >= 0:
x = int(str(x)[::-1])
else:
x = - int(str(-x)[::-1])
"""

return x if x < 2147483648 and x >= -2147483648 else 0
"""
if x < 2147483648 and x >= -2147483648:
x=x
else:
x=0
return x
"""
# 利用Python的字符串反转操作来实现对整数的反转,反转后的字符串要重新转换为整数。
# 负数倒序时要先转正数
# 同上面一样,要注意正负和溢出情况。

****

-->