In a previous post I spoke about the way in which we can reverse a string in JavaScript. When I wanted to learn the way to reverse an integer in JavaScript I realized right from the start that this would be different than reversing a string. There are some tricks that someone needs to understand in order to get this to work.
Here are some examples of how I want this to work. If I make a function called reverseInt, I want it to be able to do the following:
reverseInt(23) === 32
reverseInt(904) === 409
The first trick that I wanted to try was to turn the number into a string. The reason I wanted to do this was so that I would have the same abilities now with this integer that I had when I reversed a string. Let me start out by declaring a variable called number.
Then I’ll call the toString() method on this variable and .split(‘’) the same way I did when I reversing a string which looks like the following:
We can now work on this number the same way we could with a string like using reverse().
There is another trick however. What if the number is negative? There is a method called Math.sign which handles numbers in the following way:
Math.sign(1000) = 1
Math.sign(-1000) = -1
Why is this important? This is important because if we are given a negative number, we have to be able to handle that case.
Here is my code which can show my first set of steps:
This won’t work however because if we are given a negative number like -13, we will receive 31- as the output which is what we do not want. The last trick I haven’t spoke about which is something we need to complete this is the parseInt method. This will turn our string back into an integer which is what we’re looking for. The entire function can now be written in the following way:
This is a quick overview of how to reverse a string. For the documentation on Math.sign and parseInt see the links below. Thanks for reading!