 Image Credits: CarfromJapan

To solve the reversed integer and reversed string algorithms, we would need to refer to some of the Logic we used in Part 1 of this series, click here to see the post.
I’d be dealing with the more complex algorithm which is reversing an integer before solving reversing a string, in fact, if you can reverse an integer you should have no problem reversing a string.

Question 1.

Write a function to reverse an Integer

As seen in our previous article, reverse an integer follows pretty much a very similar logic.
The first thing I’d do is to convert the number to a string by calling the inbuilt JavaScript .toString() in-built method.

let myNumber = 23

const myChar = myNumber.toString()

// OUTPUT = "23"


When we call this method, we would notice the output returns a value in quotes, this means our value has been converted from a number to a string.

Next, we would call the following methods .split('') (this turns the string into an array, .reverse()(this would reverse the array), .join('') (this would convert the reversed array back to a string.

let myNumber = 23

let myChar = myNumber.toString().split('').reverse().join('')

console.log(myChar)
// returns 32

console.log(typeof(myChar))
// returns string


So we have successfully reversed the number but the output is still a string and not a number, meaning we cannot perform mathematical operations on our result. To change this back to a number, we would simply wrap this into the JavaScript parseInt() method.

const myNewNumber = parseInt(myChar);

console.log(myNewNumber);
// returns 32

console.log(typeof(myNewNumber))
// returns number


Handling edge Cases

If you clone this repository, install the dependencies and run yarn run rev-int you’d notice at least one test failing with our current implementation. And that is the reversal of negative numbers.

let myNumber = -23

let myChar = myNumber.toString().split('').reverse().join('')

const myNewNumber = parseInt(myChar);

console.log(myNewNumber);
// returns 32


So our current implementation is not capturing for negative numbers, we would want the reversal of -23 to return -32 for us.
One fix for this would be to multiply our results by negative 1 if the number is less than 0.

const reversedInt = (n) =>{
const reversed = n.toString().split('').reverse().join('');
if(n < 0){
return parseInt(reversed) * -1;
}
return parseInt(reversed);
}


Question 2

Write a function to reverse a string

We just need to call 3 in-built methods to get this done.

const reverseStr = str => {
const arr = str.split('').reverse().join('');
return arr;
}


Do not forget to clone this repository and try to solve some of these algorithm problem using your own method making sure they pass all the test cases.

Repository: https://github.com/seunzone/js-algorithms