[Leet Code] Reverse Integer

Matthew Boyd
2 min readDec 31, 2020

--

Leetcode: https://leetcode.com/problems/reverse-integer/

Problem:

Given a 32-bit signed integer, reverse digits of an integer.

Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Solution:

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
list_str = list(str(x))
answer = 0
if "-" in list_str:
list_str.remove("-")
list_str.reverse()
list_str.insert(0,"-")
answer = int("".join(list_str))
else:
list_str.reverse()
answer = int("".join(list_str))
if answer < -2147483648 or answer > 2147483648:
return 0
else:
return answer

Explanation:

So, there are a few edge cases that makes this solution a little lengthy, but let’s step through it. First we take the list of integers, and we cast it to a string and a list. We also create an answer variable. We check if there’s a “-” in the list, this will tell us if it’s a negative number. If there is, we remove the “-”, then we do the reverse method on the string, then we add the negative character back in at the start of the list. Then we join the list together to create a string and cast that to an int. Otherwise, if it isn’t negative, we do the same without the removal and insertion of the “-” sign. Then lastly, we get the answer variable, and we make sure that it’s 32 bits long, how we get these numbers is 2 ** 32 and 2 ** -32, provided it’s within these parameters, it’s a 32 bit integer.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet