
LeetCode: Reversing Integers with JavaScript

For those of you who've been knee‑deep in the world of web development, juggling with data types like integers might seem a bit rudimentary. After all, we're often more engrossed in CSS quirks, JavaScript frameworks, or responsive designs than we are concerned over basic numerals.
However, algorithms form the backbone of many operations we see on the web, whether it's search functionality, data sorting, or even some fancy animations. One such seemingly simple, yet intriguing problem is the 'Reverse Integer' problem.
Understanding the Problem
Imagine you've been given a 32‑bit integer, and your task is to reverse its digits, whilst returning a 32‑bit integer. Sounds simple enough, right? If you have the number 123, your function should return 321. For ‑123, the output should be ‑321.
However, the catch here is in dealing with the constraints and edge cases. What happens when the number is too large or too small? How do you efficiently handle negative numbers or zeroes at the end of the reversed integer? These nuances are what make the problem interesting and relevant, and can reveal more about your critical thinking and problem‑solving in an interview environment than you might first think...
This type of task is crucial in web development, especially when dealing with data transformations, validations, or encryption mechanisms. Being confident in our ability to manipulate and transform basic data types is foundational for building robust web applications.
Constraints
- The reversed integer should remain a 32‑bit integer.
- If reversing the integer causes it to go out of the bounds of a 32‑bit signed integer, then return
0. The range of 32‑bit signed integers is from‑2^31to2^31‑1, or‑2,147,483,648to2,147,483,647.
Key points
To solve this problem, you need to reverse the digits, not the whole number. For example, the reversed version of ‑123 is ‑321, not 321‑. Be mindful of integer overflow. If the reversed number doesn't fit within the 32‑bit integer range, return 0.
A Solution Using TypeScript and ES6
I tend to develop more or less entirely in TypeScript now, which takes away one of the issues this problem presents: incorrectly‑typed inputs. Here, we're expecting the input to be a number.
function reverseInteger(x: number): number { let reversed: number = 0; while (x !== 0) { reversed = reversed * 10 + (x % 10); x = Math.trunc(x / 10); } // Checking for integer overflow if (reversed < (-2) ** 31 || reversed > 2 ** 31 - 1) { return 0; } return reversed;}How It Works
- We initialise a variable
reversedto store our reversed number. - The while loop is used to reverse the digits of the number.
- We then multiply the reversed number by
10and add the last digit of the original number to it. - The original number is then divided by
10(using truncation to discard the decimal part). - We iterate through this loop until the original number becomes zero.
- Finally, there's a check to ensure our reversed number doesn't overflow the 32‑bit integer limit. If it does, we return
0.
Another Approach
Above, I've focused on a mathematical solution: manipulating the numbers to produce the desired output. There is another option that will achieve just the same result with a little more type manipulation.
The Code
const reverse = (x: number): number => { // Convert the number to string, reverse it, and parse it back to an integer let reversed: number = parseInt( Math.abs(x).toString().split('').reverse().join('') ); // If the input number was negative, make the reversed number negative if (x < 0) { reversed = -reversed; } // Check for 32-bit signed integer boundaries const INT_MIN: number = (-2) ** 31; const INT_MAX: number = 2 ** 31 - 1; if (reversed < INT_MIN || reversed > INT_MAX) { return 0; } return reversed;};How It Works
Convert to String and Reverse:
Since JavaScript does not have a direct way to reverse numbers, you can convert the number to astring, then to anarray, then reverse thearray, and finally, join it back together to get a reversed string.Check Negative Numbers:
If the input number is negative, handle it appropriately.Boundaries Check:
Ensure that the reversed number is within the 32‑bit signed integer range.
It's worth noting that I'm using Math.pow to calculate the power of 2. I feel that in many practical scenarios, the 32‑bit integer limits will be provided to you, or they could even be hard‑coded, rather than needing to be calculated every time the function is called.
Overall, this is perhaps a simpler and easier‑to‑understand solution, although it won't be as performant when it comes to dealing with larger inputs.
Wrapping up
Algorithms, even as fundamental as reversing an integer, play a vital role in the world of web development. They strengthen our problem‑solving muscles and better prepare us to tackle more complex challenges on the web.
Categories:
Related Articles

Using the filter() Method in JavaScript. Using the

Controlling Element Transparency with CSS opacity. Controlling Element Transparency with CSS
opacity
How to Prevent Race Conditions in JavaScript with AbortController. How to Prevent Race Conditions in JavaScript with
AbortController
Using next/link for Client‑Side Navigation. Using
next/linkfor Client‑Side Navigation
Rethinking Carousels: Going Around in Circles. Rethinking Carousels: Going Around in Circles

Vue 3 Reactivity: Proxies vs. Vue 2 Reactivity. Vue 3 Reactivity: Proxies vs. Vue 2 Reactivity

Check If a String Contains Only Whitespace with JavaScript. Check If a String Contains Only Whitespace with JavaScript

What Does a Software Engineer Do? What Does a Software Engineer Do?

A Beginner's Guide to Web Hosting. A Beginner's Guide to Web Hosting

React Fragments Explained. React Fragments Explained

Enhancing Web Typography with text‑wrap: balance. Enhancing Web Typography with
text‑wrap: balance
Building Custom Hooks in React. Building Custom Hooks in React