Reverse Integer solution explained

The Reverse Integer solution pops the last decimal digit with % 10, pushes it onto a result with result * 10 + digit, and, before every push, checks that the push cannot leave the signed 32-bit range; if it would, the answer is 0. The check is done by comparing the current result with (limit - digit) / 10, so the code never needs a value larger than 32 bits. It takes O(number of digits) time, at most 10 steps, and O(1) memory.

By Published 8 min read

The problem in plain words

You get an integer x that fits in a signed 32-bit type, so it lies between -2,147,483,648 and 2,147,483,647. Reverse the order of its decimal digits, keep the minus sign if there was one, and drop any zeros that end up at the front. If the reversed number would fall outside the 32-bit range, return 0. The usual extra rule is that you should pretend the environment cannot store anything wider than 32 bits, so you may not compute the reversal in a 64-bit variable and check afterwards.

Examples computed with the code on this page
InputOutputWhy
30722703The middle zero stays in place
-581-185The sign is kept
10001Trailing zeros become leading zeros and disappear
14638474122147483641Fits, just under the maximum
14638474130Reversed would be 3147483641, too large
21474836470The reversal starts with 7 and has ten digits, too large
-21474836480The reversal is far below the minimum
Examples computed with the code on this page. Scroll sideways on a small screen.

What the interviewer listens for

Anyone can reverse a string. The question is a disguised overflow test: will you notice that reversing a valid 32-bit number can produce an invalid one, and can you detect it without cheating with a bigger type? Interviewers also watch how you handle negative numbers, since division and remainder on negatives behave differently from language to language. A candidate who says this out loud before coding usually scores well even if the code needs a small fix.

Follow-up questions

  • Is the number a palindrome? Reverse only the second half of the digits and compare with the first half, which also avoids overflow.
  • 64-bit input. Same algorithm, different limits.
  • Reverse in another base. Replace 10 with the base; base 2 leads to Reverse Bits, where the width is fixed instead.
  • Parse a string to an integer with the same overflow rule. The check before each push is identical; it is the core of a classic string-to-integer problem.
  • Why not take the absolute value first? In a 32-bit language, the absolute value of the minimum does not fit. Work with the sign, or use the method below.

The easy version: through a string

Take the absolute value, turn it into text, reverse the text, convert back to a number, reapply the sign and compare with the limits. In Python or JavaScript this works because the intermediate number can be larger than 32 bits. It is a good opening sentence, and the moment to point out that it breaks the "no wider type" rule, which is what the next version fixes.

def reverse_by_text(x):
    sign = -1 if x < 0 else 1
    value = sign * int(str(abs(x))[::-1])  # relies on Python's unbounded ints
    return value if -2**31 <= value <= 2**31 - 1 else 0
String reversal: correct, but the check happens after building a possibly oversized number.

The expected version: check before each push

Pop the last digit of x with a remainder, remove it with a division, and push it onto the result with result * 10 + digit. The push is safe only if result * 10 + digit stays within the limit. Rearranging gives result <= (limit - digit) / 10, and since result is a whole number you can compare it with the whole part of that fraction. Nothing in the comparison is bigger than the limit itself, so it works in strict 32-bit arithmetic.

The Python version works on the magnitude and keeps the sign aside, choosing 2^31 - 1 as the limit for positive inputs and 2^31 for negative ones. Python's integers have no fixed size, so this is a faithful model of the check rather than a necessity; in C or Java, avoid taking the absolute value of the minimum.

def reverse_digits(x):
    limit = 2**31 - 1 if x >= 0 else 2**31  # largest magnitude the answer may have
    remaining = abs(x)
    result = 0
    while remaining:
        digit = remaining % 10
        remaining //= 10
        if result > (limit - digit) // 10:
            return 0  # result * 10 + digit would leave the 32-bit range
        result = result * 10 + digit
    return result if x >= 0 else -result
Python: digit by digit with a pre-push check. O(log10 |x|) time, O(1) memory.

The JavaScript version works on the signed value directly. In JavaScript, x % 10 keeps the sign of x, and Math.trunc rounds toward zero, so for negative x every digit comes out negative and the result grows toward the minimum. A negative input is therefore checked against the lower limit and a positive one against the upper limit. Picking the check by sign keeps MIN - digit and MAX - digit inside the 32-bit range. Truncation toward zero gives the right bound on both sides: for the upper limit it rounds the fraction down, and for the lower limit it rounds it up, which is exactly what each inequality needs. JavaScript numbers are really 64-bit floats, so this code is a faithful model of the 32-bit check rather than a proof of it.

function reverseDigits(x) {
  const MAX = 2147483647;
  const MIN = -2147483648;
  const negative = x < 0;
  let result = 0;
  while (x !== 0) {
    const digit = x % 10; // same sign as x in JavaScript
    x = Math.trunc(x / 10);
    if (negative) {
      if (result < Math.trunc((MIN - digit) / 10)) return 0; // MIN - digit >= MIN
    } else if (result > Math.trunc((MAX - digit) / 10)) {
      return 0; // MAX - digit <= MAX
    }
    result = result * 10 + digit;
  }
  return result;
}
JavaScript: signed digits, checked against the limit on the same side as the input.

Cost of each approach

For an input with d decimal digits (at most 10 for 32-bit values)
ApproachTimeExtra memoryWithin 32 bits?
String reverse and parseO(d)O(d) for the stringNo; relies on a wider type for the comparison
Pop, check, pushO(d)O(1)Yes
Compute in 64 bits, check at the endO(d)O(1)No; often explicitly disallowed
For an input with d decimal digits (at most 10 for 32-bit values). Scroll sideways on a small screen.

Edge cases

  • 0, which should return 0 without entering the loop.
  • Inputs ending in zeros, such as 1000, whose reversal is shorter.
  • The largest and smallest 32-bit values, both of which overflow when reversed.
  • Values whose reversal lands just inside the limit, such as 1463847412, to confirm the check is not off by one.
  • Single negative digits such as -7, which must stay -7.

Common slips

  • Checking for overflow after the multiplication, when in a 32-bit language the damage is already done.
  • In Python, using % and // directly on a negative x. Python's remainder of -581 by 10 is 9, not -1, because it rounds toward negative infinity; work with the magnitude instead.
  • Taking the absolute value of the minimum 32-bit value in a language where it does not fit.
  • Comparing only against the upper limit and forgetting that negative results can overflow too.
  • Returning -0 in JavaScript for some inputs and printing it oddly. With the code above, no input produces it, which was checked.

How to explain it out loud

Fictional example

Leading with the overflow concern
Candidate
Reversing a valid 32-bit number can produce something out of range, like reversing the maximum. So I'll pop digits with modulo ten and push them onto a result, and check before every push.
Candidate
The push is result times ten plus the digit. It's safe only if result is at most the limit minus the digit, divided by ten. That comparison never builds a number bigger than the limit, so it works even in pure 32-bit arithmetic.
Candidate
For negatives I have to be careful because languages round division differently. In JavaScript I'll let the digits be negative and check the lower bound too. At most ten digits, so constant time in practice.

Reverse Bits is the binary cousin with a fixed width. Sum of Two Integers is another problem about how 32-bit values behave at their edges. Encode and Decode Strings also turns numbers into text and back, as length prefixes in front of each string.

Natively for practice

Overflow checks are the kind of detail that slips under time pressure. In a practice round on Mac or Windows, Natively can read the problem from a screenshot, help you derive the pre-push inequality instead of memorizing it, and suggest boundary inputs to trace. Reading its transcript of your mock afterwards makes it easy to see whether you raised the overflow risk before writing code.

Questions people ask

How do you reverse an integer without overflow?

Pop the last digit with % 10, and before pushing it with result * 10 + digit, check that result is at most (limit - digit) / 10, rounded toward zero. If the check fails, return 0.

Why does Reverse Integer return 0 for some inputs?

The rule is to return 0 when the reversed value falls outside the signed 32-bit range. For example, reversing 2147483647 would give a ten-digit number starting with 7, which is too large.

How do you handle negative numbers in Reverse Integer?

Either reverse the magnitude and reapply the sign, or let the digits be negative, as JavaScript's % and Math.trunc produce, and check against the lower limit as well. Avoid taking the absolute value of the minimum in fixed-width languages.

Can I solve Reverse Integer by converting to a string?

It works in Python and JavaScript and is a fine first answer, but it relies on a number wider than 32 bits during the check, which the usual version of the problem does not allow.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP