LeetCode Reverse Integer

Adam James
3 min readJun 5, 2021

Coding challenges like LeetCode or HackerRank are great ways to solidify coding principles and learn more ways to problem solve in efficient ways. Throughout my job search, I’ve been trying to do as many challenges as I can. Including one to reverse a given integer that gave me a little bit of trouble.

The prompt for the Reverse Integer challenge on LeetCode is as follows:

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231–1], then return 0.

For example, if x = 321, the function will return 123. If x = -123, the function will return -321.

My initial impulse was that I should split the given number x into an array, reverse that array, then rejoin the string. Returning this new variable would give me the exact number that was initially given, but reversed.

Initial Attempt at a Solution

I ran into a couple issues with this initial idea. First off, the returned value with this variable being returned would give me a string instead of an integer, which the solution would be looking for. Apart from that larger issue, the function wouldn’t return 0 when outside the designated range and more importantly, when given a negative number the sign would be at the back of the number instead of the front.

Oops!

The first issue I decided to confront was the designated range problem. I knew from reading the constraints that anything outside of the 32-bit range would be greater than 2³¹, so I added that as an if statement inside the function.

Getting Closer…

This still meant that I had an issue with the proper signage for the returned number, along with the issue of the returned number still being a string. I tried a few different workarounds, initially trying to use pop and unshift to remove the “-” from the end of the reversed string and sticking it back in front. After a bit of googling, I stumbled across a great solution to my problems by using the built in Math JavaScript object.

Finished!

Instead of removing the negative through pop or shift, running Math.abs(x) gives the absolute value of the number between the parentheses, which is the distance from zero that a number is (meaning that it removes the negative sign on any negative number). To add that sign back on, you can run Math.sign(x). Math.sign either returns 1 for a positive number, 0 for 0, or -1 for a negative number. Multiplying the reversed string of a negative number by -1 will give you a negative integer and return a successful submission.

--

--