· By John Kavanagh

LeetCode: Reversing Integers with JavaScript

A 3D illustration of rows of small red arrows pointing right against a dark background.
Image by 愚木混株 cdd20, licensed from Unsplash.

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...

Reversing decimal digits isn't something I often need in application code. The useful exercise is reasoning about a numeric limit before an operation crosses it. That detail matters more here than finding a neat way to reverse the digits.

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^31 to 2^31-1, or -2,147,483,648 to 2,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. All three 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

  1. We initialise a variable reversed to store our reversed number.
  2. The while loop is used to reverse the digits of the number.
  3. We then multiply the reversed number by 10 and add the last digit of the original number to it.
  4. The original number is then divided by 10 (using truncation to discard the decimal part).
  5. We iterate through this loop until the original number becomes zero.
  6. 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

  1. Convert to String and Reverse:

    Since JavaScript does not have a direct way to reverse numbers, you can convert the number to a string, then to an array, then reverse the array, and finally, join it back together to get a reversed string.
  2. Check Negative Numbers:

    If the input number is negative, handle it appropriately.
  3. 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.


Checking Before the Next Multiplication

The two versions above give the right result in JavaScript, but they only reject an oversized value after constructing it. I'd use the following version for the original challenge. It makes the same digit‑by‑digit calculation, with the overflow decision moved in front of the multiplication.

The largest allowed result is 2147483647. Before appending another digit, a positive reversed must therefore be below 214748364, or equal to it with a final digit no larger than 7. The negative limit is -2147483648, which allows a final digit down to -8 when the prefix is -214748364. That asymmetry is why the two checks differ.

const reverseInt32 = (x: number): number => {
  let reversed = 0;

  while (x !== 0) {
    const digit = x % 10;
    x = Math.trunc(x / 10);

    // Check the prefix and final digit before forming the next value.
    if (
      reversed > 214748364 ||
      (reversed === 214748364 && digit > 7) ||
      reversed < -214748364 ||
      (reversed === -214748364 && digit < -8)
    ) {
      return 0;
    }

    reversed = reversed * 10 + digit;
  }

  return reversed;
};

Keeping Negative Values Negative

JavaScript's remainder keeps the sign of the input: -123 % 10 is -3. Math.trunc(-123 / 10) gives -12, which is the remaining number we want. Math.floor would give -13, so it isn't interchangeable here. For -120, the extracted digits are zero, -2, and -1; the accumulator becomes zero, -2, and finally -21.

There's no need to take an absolute value or restore the sign afterwards. Avoiding that conversion also avoids turning -2147483648 into the out‑of‑range positive value 2147483648. JavaScript still represents these values as number, but the algorithm never needs an integer value outside the signed 32‑bit range. It doesn't rely on a wider integer holding a failed reversal.

For an input of zero, the loop never runs and the function returns zero. Trailing zeroes disappear naturally because an integer has no separate place to store them. Each pass removes one digit, so this version takes O(d) time for d decimal digits and O(1) extra space. Under the stated input limit there are at most ten passes.

For comparison, the earlier string‑based version also takes O(d) time, but it creates an array of d digit characters and intermediate strings, giving O(d) extra storage. The arithmetic versions keep only a fixed number of numeric variables. The signed 32‑bit input limit bounds d to ten here; the distinction is still useful when explaining what each version allocates.

Trying the Awkward Inputs

The nearby inputs 1463847412 and 1563847412 are a useful pair: the first reverses to 2147483641, but the second would produce 2147483651 and must return zero. Run these checks after the function to cover that difference, both signs, trailing zeroes, and the smallest input.

const examples: Array<[number, number]> = [
  [123, 321],
  [-123, -321],
  [120, 21],
  [-120, -21],
  [0, 0],
  [1463847412, 2147483641],
  [1563847412, 0],
  [1534236469, 0],
  [-2147483412, -2143847412],
  [-2147483648, 0],
];

for (const [input, expected] of examples) {
  const actual = reverseInt32(input);
  if (actual !== expected) {
    throw new Error(`Unexpected reversal for ${input}: ${actual}`);
  }
}

Checking the returned value alone doesn't prove the storage restriction is satisfied. In my verification, a separate string‑and‑BigInt calculation supplied the expected answers, whilst an instrumented copy checked the arithmetic intermediates. The test oracle can use wider storage; the published function above doesn't. That's also why the earlier implementations remain useful comparisons rather than examples to submit under the stricter rule.


Wrapping Up

The interesting part isn't reversing the digits. It's deciding whether the next step is allowed before taking it. The earlier examples make JavaScript's wider numeric storage convenient; the guarded version makes that convenience unnecessary for this problem.

Postscript

November 2026: I've added a version that checks for overflow before multiplying, including the unequal positive and negative limits. The original examples are still here for comparison, with executable cases showing where the stricter version accepts a reversal or returns zero.

Want to find out more?

If you need senior hands‑on support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.