Solving Reverse Integer Algorithm

JakePino
2 min readMar 20, 2021

Today, I want to talk about a problem which, according to leetcode.com, is a fairly common interview question. This problem is known as Reverse Integer on leetcode, let’s take a look.

The Problem

As pictured above, the problem would like for us to write a function that takes in an integer, and and returns an integer that is a numerically reversed version, but with the same positive/negative value. So if we gave the function an integer of 321, it would return an integer of 123. If we gave it -468, it would return -864. It also asks that we keep it within the 32-bit range.

The Solution

The solution for this is fairly straightforward but good to go over nonetheless. We start by creating an empty array, which we will call reversedArr. We then create an array, called xArr, which is the result of us converting the given integer into a string, and then splitting it. We then use a for loop to iterate over xArr and using the unshift method, we put each element of xArr into the reversedArr. By using unshift, each new value is put into the front of the reversedArr, so by the end of the loop, the values will be a reversed copy. Because had converted our integer into a string in order to split it, we now will use parseInt and the join method to turn it back into an integer value, called reverse. Now because we need to make sure the reverse value is within 32-bits, so we use the given constraint of 2³²-1, and check if our reversed value is greater than that constraint. If it is, return 0. If not, we check if the original input was positive or negative and return our reversed value with the same value. The end result looks like this:

Our solution ran at about 96 ms, roughly faster than 80% of the submissions up to that submission date. I hope this was helpful! Keep hitting the algos.

--

--

JakePino

California native, living in NYC., Software Engineer.