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
I tend to work in TypeScript, so the parameter is declared as number. That checks calls at compile time; it does not validate a value arriving at runtime or restrict numbers to integers. Both examples assume a finite, signed 32‑bit integer between -(2 ** 31) and 2 ** 31 - 1. Validate untrusted input before calling them, for example with Number.isInteger(x) and those range checks.
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.
Both examples use the exponentiation operator, **, to calculate the signed 32‑bit limits. 2 ** 31 means two raised to the power of 31; the lower bound is -(2 ** 31) and the upper bound is 2 ** 31 - 1. These limits could also be named constants shared by the functions.
There is a storage assumption to be clear about. The original LeetCode problem rules out storing a wider integer. These JavaScript versions form the reversed value first and check the range afterwards. A signed 32‑bit input has at most ten decimal digits, so its reversal is below 10 ** 10, well within Number.MAX_SAFE_INTEGER. That makes the intermediate exact here, but it relies on storage beyond 32 bits. A solution obeying the stricter restriction must check the next digit against the limits before multiplying and adding.
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.