DEV Community

Seth
Seth

Posted on

Reverse Integer

Don't get scared when it tells you that the integer is 32 bit. I had no idea what this was at first, but it just means the number has an upper bound and an lower bound number, meaning there are limits to its largest and lowest numbers.

We will start with the base case.


const reverse = (x) => {
 if (x < 0) return -1 * reverse(-x)
}
Enter fullscreen mode Exit fullscreen mode

This line is important. If the number is negative, we will want to turn it into a positive number so we can break out of the if loop.

const reverse = (x) => {
 if (x < 0) return -1 * reverse(-x)
 const solution = x.toString().split('').reverse().join('')

}
Enter fullscreen mode Exit fullscreen mode

Next we will turn the number into a string, split it, reverse, then join it back together.

Now let's finish it out.

const reverse = (x) => {
 if (x < 0) return -1 * reverse(-x)
 const solution = x.toString().split('').reverse().join('')

 if (solution > 2 ** 31 - 1) {
  return 0
  } 
  else {
 return solution
 }
Enter fullscreen mode Exit fullscreen mode

The number has an upper bound of 2^31 -1. So, if the solution is greater than the upper bound we return 0. This is because it's too large to be in the bounds of our answer.

If it's less, we can just return the solution.

Top comments (2)

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

You have an error in last example. Missing closing brace. you will see it, it you would use proper indentation.

This is your code with fixed indentation:

const reverse = (x) => {
    if (x < 0) return -1 * reverse(-x);

    const solution = x.toString().split('').reverse().join('')

    if (solution > 2 ** 31 - 1) {
        return 0
    }
    else {
        return solution
    }
Enter fullscreen mode Exit fullscreen mode

Anther thing is that you return string instead of number.

You can also use syntax hightliting see: A Beginners guide to the DEV editor.

Collapse
 
seth_king profile image
Seth

Thank you! I write these directly on dev.to's blogging platform where it doesn't highlight for you the closing brackets/opening brackets so I have to do it all by eye. Cheers.