reverse integer – leetcode a7

Problem

Problem description

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 :
def reverse(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):
ans = 0
break
return ans*sign

Python Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class :
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
MaxInt = (1<<31)-1
MinInt = -(1<<31)
if x > 0:
ans = int(str(x)[::-1])
else:
ans = int(str(-x)[::-1])*(-1)
if (ans > MaxInt or ans < MinInt):
ans = 0
return ans