# Reverse Integer - Python Solution&Explanation

• ### [My Thoughts..]

Given x is number and type is 'integer'.

1. Make x to string and reverse it. Make it to a number. Define it as 'r' (r is a result) .

• Question1: if x<0 ?
For example, if x is -120 and reverse it, it becomes '021-'.

• Answer1: If x<0, use abs(), reverse it and make it to a number and add ' - ' in front of it.

• Question2: How to convert '021' to an integer? Does it start with '0'?
``````             >>> int('021')
21
``````

2. "Note" says, "integer within the 32-bit signed integer range" : Judge the length of binary number of 'r' whether it is in range of 0 ~ 31

• Question1: If r<0 (r is a reversed integer) and convert it, for example, ' -11 ' will be ' 11- '.
• Answer1: Use abs() and make it to a binary number.

• Answer2: We don't need '0b'. Therefore, len(bin(abs(r))) - 2

3. If it is in range of 0~31, return 'r'.
If it is not in range of 0~31, return 0

### [My Solution is..]

``````class Solution:
def reverse(self, x):
self.x=x

if x<0:
r=-int(str(abs(x))[::-1])
else:
r=int(str(x)[::-1])

if len(bin(abs(r)))-2 in range(32):
return r
else:
return 0
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.