Integer Reversal ― The Ultimate Guide to JavaScript Algorithms

### Table of Contents

Reversing an integer usually comes across as an easy thing to do for most developers. However, on closer evaluation, it gets a little tricky due to certain requirements and constraints involved. This article addresses these by providing a step-by-step explanation of the process behind reversing an integer in JavaScript.

You should already have your development environment setup for this course. Open the cloned repository and inside the `Beginner`

folder, navigate to the `IntegerRevesal`

folder. Our work for this challenge will be done in here. Make sure to follow along in the `index-START.js`

file.

## The Challenge

Given an integer, return an integer that has the reverse ordering of that which was received. E.g

`reverseInteger(-123) // should return -321`

Keep the following rules in mind:

- The signs must not change i.e -123 becomes -321
- The value returned must be an integer.
- All insignificant zeroes must be removed i.e 900 becomes 9 and not 009

## Algorithmic Thinking

To solve this challenge, we are expected to write a function which accepts the number to be reversed and returns the reversed number as the result.

There is no way to directly reverse an integer in JavaScript without some clever manipulation or computation. Earlier, we learned how to reverse a string and we even went further to determine the optimal approach. This will come in handy for this challenge.

Theoretically, we can reverse an integer by applying the following steps:

- Convert the Integer to a string
- Create and array of characters from the string
- Reverse the array
- Join the reversed array to form a new string
- Convert the reversed string back into an integer
- Add the sign that corresponds with the received integer
- Return the result

**Seems overwhelming? It’s really not. Let’s walk through the implementation together.**

## Code Implementation

In our string reversal challenge, we determined the optimal way to reverse a string to be with the `.reduce()`

method as shown below:

```
function reverseString(text) { return [...text].reduce((acc, char) => char + acc, '')
}
```

Applying this in solving this challenge,we shorten the steps to be followed from what we have above into 4 steps:

- Convert the integer to a string
- Reverse the string
- Convert back to an integer
- Return the reversed integer with a corresponding sign as the received.

We shall now follow these steps in coming up with a solution for this challenge as shown below.

**Let’s get coding**!

## Convert the Integer to a String

The .toString() method in JavaScript is used to convert a number to its string equivalent in any number base(radix) between 2 and 36 as specified. If the radix is not specified, the default radix is assumed to be 10.

To convert the integer to a string, we call this method on the received number as shown below:

`num.toString()`

Applying this step to the challenge sample gives a string `"``-123``"`

.

## Reverse the String

To reverse the string we’ll apply the optimal method as determined in the “String Reversal” challenge. We simply pass in the converted string as shown below:

```
// Reversing a string using .reduce()
function reverseString(text) { return [...text].reduce((acc, char) => char + acc, '')
}
// Calling the function on the string equivalent of the integer to be reversed
let reversedString = reverseString(num.toString())
```

This step reverses the string from the previous step, so we have `"``321-``"`

.

## Convert back to an Integer

To convert back to an integer, we used the `parseInt()`

function to convert the reversed string back into an Integer.

The **parseInt()** function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems) if any.

`let reversedNumber = parseInt(reversedString)`

When we convert the reversed string above back to an integer, we have `321`

. Notice that this gets rid of the negative sign at the end. Thus, in the next step we add the corresponding sign to the reversed integer.

This is the final step in reversing an integer. Using the `Math.sign()`

function, we are able to determine the sign on the number that was received. With that we can adjust our `reversedNumber`

accordingly.

The **Math.sign()** function returns the sign of a number, indicating whether the number is positive, negative or zero. It returns 1 for positive, -1 for negative and 0 for a zero value.

`Math.sign(num)`

We can automatically convert the `reversedNumber`

to possess same sign as the number that was received by multiplying it by the value returned by `Math.sign()`

above. i.e

`return (reversedNumber * Math.sign(num))`

The statement above does the conversion and returns the result from the function as the final answer. For our challenge sample, `Math.sign(num)`

returns `-1`

. When we multiply `-1`

by `321`

we have `-321`

, which is the correct answer(i.e the reversed integer).

**Now we are finally done**!** Here’s the complete solution:**

```
// Reverses a string
function reverseString(text) { return [...text].reduce((acc, char) => char + acc, '')
} // Reverses an integer
function reverseInteger(num) { let reversedNumber = parseInt(reverseString(num.toString())) return (reversedNumber * Math.sign(num))
}
```

Notice how we’ve compressed things a little more to make the solution more concise.

## Testing

## Testing Correctness with Jest

To execute the tests for this challenge, simply run the following command from your terminal

`npm run test IntegerReversal`

The results reveal that we passed all tests.

## Testing Performance with Jest

Since we considered only one approach to solving this challenge, we carry out no performance comparison.

## Practical Application

This challenge is simply a variation of the string reversal challenge and may be used used to test an understanding of JavaScript in coding interviews.

## Conclusion

We have now successfully implemented the solution to this challenge despite its unique constraints. Feel free to explore more ways and share in the comment section below. Stay tuned for more mathematical challenges to follow.

## Further Reading

For further learning on the techniques and concepts applied above, you may use the following links:

**See you in the next one**!**✌🏿**