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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Python “C-style” Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class :
defreverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if (x < 0):
sign = -1
x = -x
ans = 0
while (x > 0):
ans = ans * 10 + x % 10
x = x // 10
if ans*sign > ((1 << 31) - 1) or ans*sign < -(1 << 31):
近期评论