How to Reverse Integer in Javascript!

Faizah Ahsan
2 min readSep 13, 2020

Reverse questions are very common during interviews. These questions might sound intense and complicated, but it actually is not hard if you know a few tricks and tricks and keep on practicing them. Here is another reverse problem like the classic string reversal problem, except there are a few differences which I will be showing below.

The question:

Given an integer, return an integer that is reverse ordering of numbers.

Example:

reverseInt(20) === 02

reverseInt(135) === 531

reverseInt(-13) === -31

reverseInt(-56) === -65

Solution:

To reverse the number the first thing we need to do it in our function is to convert the number into a string with .toString(). Now we we have a string so we can do .split(“ ”) to get and array and do .reverse() and .join(“ ”) on the string.

After doing the last step we have a reversed string but we will need to convert it into a number. To do that we will need to save the string into variable. So I have saved it into variable called reversed in the above example. To covert the reversed string into a number we will need to use the parseInt() function and return it.

This we will pass the tests for those number above 0. But for the numbers below 0 we will need to do one last step which is Math.sign(). Math.sign() is a standard Javascript function. If we pass in a negative number in this function it will return a negative number. If we pass in a positive number it will return a positive number. So for this problem we will just multiply the math.sign() with returned number. This way it will check and return the positive or negative number.

This is one way to solve this problem, there are many others way you can solve this problem.

--

--

Faizah Ahsan

Junior Full-Stack Web Developer. Looking for opportunities!