Integer Reversal Algorithm

Natalia Wit
3 min readJan 11, 2021

In this week's blog, we are going to go over the integer reversal algorithm question that may seem easy at first but there are a few tricky issues you may run into when approaching the problem.

We will be working with the following question:

Directions:Given an integer, return an integer that is the reverse ordering of numbers.Examples:reverseInt(19) === 91reverseInt(281) === 182reverseInt(300) === 3reverseInt(-15) === -51reverseInt(-70) === -7
function reverseInt(n) {
//Code goes here
}

In the given examples above we can see that if we pass in 19, we should get a reversal result of 91, but things may get a little tricky when we run into negative numbers or numbers with zeros at the end. One thing we need to make sure of is our end result should always output a number rather than a string. So you can see that there are many cases we need to look into when approaching this problem.

There are a few thoughts that go into my head when approaching this problem. We can use the trick of turning a number into a string and using a few string methods as the first steps.

Helpful String Methods

Let’s start working on the problem:

The first thing we are going to do is give the ability to reverse a number. To reverse a number, we are going to use the approach I showed you above.

We are going to turn the number into a string by using the toString() method and split that number (in other words already a string) into an array by using the split('') method, use the reverse() method on it and then join it back together by using the join('')

Let me demonstrate below:

Partial Solution 1

You may have thought that our job was done here but what’s happening above is that when we are inputting a number we are getting a string back and our negative sign at the end. OH NO!

Let’s go ahead and give this a fix

Partial Solution 2

Ok now it looks like we are getting a number back, but we are still not getting the right result since our negative sign is gone!

We can fix that →

There is a method in JavaScript that may be very helpful to fix this → Math.sign(). This method returns either a positive or a negative 1 (depending on if a negative or positive number is passed in as an argument into the method).

  • If the argument is positive, returns 1.
  • If the argument is negative, returns -1.

In that case, we can multiply this method in our return statement and receive the correct output. See below:

Final Solution

Wow, that was smooth right?

Conclusion:

If you worked with a string reversal algorithm before, this might have been somewhat easy for you, and you knew how to approach the problem. There are many times where we run into tricky situations and JavaScript comes to the rescue with its methods. That is exactly why we love JavaScript!

I hope this blog was somewhat helpful!

Happy Coding! :)

Resources:

Math.sign() Method

String Methods

--

--