LeetCode problem #7 — Reverse Integer (JavaScript)

In this LeetCode challenge we’re asked to reverse a provided integer. Now, this is very simple in JavaScript, but a little more tricky in some of the other languages supported by LeetCode, so my solution here is simple, but perhaps bordering on cheating.

Solution

For this solution, we take the provided number, get its absolute value (that is to say, we remove any negative symbol), convert it to a string, convert that string to an array, reverse the array, join the array back into a string, parse it into a number, and re-negate it if necessary.

Sound complicated? It really isn’t. Here’s a demonstration:

-1234             // Number in
1234 // Absolute value
"1234" // String value
["1","2","3","4"] // Array value
["4","3","2","1"] // Reverse array value
"4321" // Joined array
4321 // Parsed number
-4321 // Negated number

Now here’s the code:

Now, as I said earlier, this is kind of a cheat. However, I would counter that whilst the solution might be very simple in JavaScript, it is also very efficient. In fact, at the time of writing, this solution is capable of running faster than 95% of submissions. In addition, I’d question why we should account for issues which will never affect us, and certainly wouldn’t mark down a candidate for presenting this answer in a JS interview.

--

--

Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.