Today’s question is taken from LeetCode (https://leetcode.com/problems/reverse-integer).
Given a 32-bit signed integer, reverse the digits of the integer. If the resulting integer is out of the 32-bit range [−231, 231 − 1], return 0. Else, return the reverse integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Example 4:
Input: 1111111113
Output: 0
The last example returns 0 because the reversed integer 3111111111 is greater than 231.
Try solving this problem yourself.
Suggested Solution
While there can be many ways to solve this problem, the solution presented here is chosen to demonstrate the following points:
- How to use the
rstrip()
method - How to use the slice notation to remove characters from a string in Python
- How to use the slice notation to reverse a string in Python
def reverse(x):
strx = str(x)
result = ''
if (strx[0] == '-'):
result = '-'
strx = strx[1:]
if len(strx) > 1:
strx = strx.rstrip('0')
strx = strx[::-1]
result = result + strx
if int(result) > 2**31 - 1 or int(result) < -2**31:
return 0
else:
return int(result)
Let’s run through the code.
First, we define a function called reverse
that has one parameter x
.
Within the function, we first convert x
to a string using the built-in str()
function. We also declared a variable called result
and assigned an empty string to it.
Next, we check if the first character (strx[0]
) in the string is the negative sign. If it is, we assign '-'
to result
and use the slice notation to remove the first character from strx
.
When we write strx[1:]
, we are asking Python to return a sliced version of strx
, starting from index 1 until the end of strx
. If you are not familiar with the slice notation in Python, check out this tutorial.
Once that is done, we check if the length of strx
is greater than 1. If it is, we use the rstrip()
function to remove any ‘0’ at the back of the string. For instance, if strx = '12300'
and we pass in '0'
to the rstrip()
function, all the ‘0’s at the back of the string will be removed. Hence, we’ll get the string '123'
as the result. We assign this result back to strx
.
Finally, we use the slice notation to reverse strx
(strx = strx[::-1]
) and concatenate the resulting string to result
(which is either an empty string or the string '-'
, depending on whether x
is positive or negative).
Once that is done, we are ready to convert strx
back to an integer using the int()
function.
If the resulting integer is greater than 231 – 1 or smaller than -231, we return 0. Else, we return the result.
If you run the statements below now,
print(reverse(123))
print(reverse(-21))
print(reverse(4500))
print(reverse(-3200))
print(reverse(1111111113))
you’ll get the following outputs:
321
-12
54
-23
0