Recently I've circled back to LeetCode to have some fun with SQL and algorithms questions and am documenting the puzzle solving journey.
This time I reviewed the 7. Reverse Integer Python which is a Medium algorithm question. Skip to the bottom for the video session if you'd prefer 😁
The Problem
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
My Thought Process
There are 3 things I believe we need to solve for here.
Reverse the Integer by casting as a string. We also need to account for negative values so I cast an absolute value of the Integer as a string
Only 32 bit Integers are allowed so add a validation check
Determine if the Integer was negative to begin with. If so, make it negative when returned
My Code
Using the 3 steps above I put together the code below which solved the puzzle in the top 94.6% responses.
class Solution:
def reverse(self, x: int) -> int:
#convert input into string
ostring = str(abs(x))[::-1]
#check if 32bit
if int(ostring) > 2**(31):
ostring = '0'
#next check if orig was negative
elif x < 0:
ostring = '-' + ostring
return(int(ostring))
Maybe you came up with a different method? Drop it in the comments below.
Thanks for checking out this blog post. If you found this post helpful please consider donating via PayPal. Any contribution is appreciated!