Member-only story

Leetcode:Reverse Integer Python Solution

Celine Surai
2 min readMay 21, 2020

--

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

Example 1:Input: 123Output: 321Example 2:Input: -123Output: -321Example 3:Input: 120Output: 21

Assume we are dealing with an environment which 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.

This is a Leetcode easy level interview problem. The best and easiest way to approach this problem is through the use of strings.

Here is a step by step approach of the solution:

Step 1: Create a variable and convert the integer into a string by storing the absolute value. Strip all the leading zeros and then reverse the string. Afterwards store the output as an integer.

def reverse_integer(n):   y = str(abs(n))   y = y.strip()   y = y[::-1]   output = int(y)

Step 2: Check if the output is in the range or not. If it is overflown return zero.

if output >= 2** 31 -1 or output <= -2** 31:

--

--

Celine Surai
Celine Surai

Written by Celine Surai

Software engineer. I write about my journey, Machine Learning, Web application development and also Python!

Responses (1)

Write a response