Start learning free

LESSON 597 OF 673 · MATH

Reverse Integer in Python: O(log |x|) with a 32-bit Check

Practice O(log |x|) Read the full explanation

You get a whole number x that fits in 32 bits. Return x with its digits in reverse order.

A minus sign stays in front. Zeros that end up at the start of the result are dropped.

32-bit integers go from -2,147,483,648 to 2,147,483,647. If the reversed number is outside that range, return 0.

Solve it without a 64-bit integer type.

 

Example 1:

Input: x = 5600
Output: 65
Explanation: Reversed, the digits read 0065.
The two zeros in front are dropped.

Example 2:

Input: x = -2408
Output: -8042
Explanation: The digits 2408 reversed are 8042.
The minus sign stays.

Example 3:

Input: x = 1000000009
Output: 0
Explanation: Reversed, it would be 9,000,000,001.
That is more than 2,147,483,647, so the answer is 0.

 

Constraints:

  • x is from -2,147,483,648 to 2,147,483,647.
  • In powers of two, that is -231 to 231 − 1.
Note:

Your solution should run in O(log |x|) time and use O(1) extra space.



Take the digits from the right, one at a time. The remainder of a division by 10 is the last digit. Dividing by 10 drops it. Each digit goes at the end of the result: result * 10 + digit.

Check before you add each digit. If result is already above 214,748,364, ten times it is too big. If it equals 214,748,364, the digit can be at most 7. Negative numbers work the same way, with -214,748,364 and -8.

Each digit takes one step, and x has about log10|x| digits, at most 10: O(log |x|) time.
Only a few numbers are kept, so the extra space is O(1).
STEP 1 OF 10
    Ctrl + Enter to check

    PYTHON · MATH

    Reverse Integer in Python, explained

    Problem overview

    The function reverse gets a whole number x that fits in 32 bits, from -2,147,483,648 to 2,147,483,647. It returns x with its digits in reverse order. A minus sign stays in front, and zeros that end up at the start of the result are dropped. If the reversed number is outside the 32-bit range, the function returns 0.

    For 5600 the reversed digits read 0065, so the answer is 65. For -2408 the answer is -8042. For 1000000009 the reversed number would be 9,000,000,001, which is too large, so the answer is 0. The statement asks for O(log |x|) time and O(1) extra space, without a 64-bit integer type.

    Approach: peel digits off the right, push them onto the result

    The remainder of a division by 10 is the last digit, and dividing by 10 drops it. To build the reversed number, take digits from the right one at a time and append each to the result with result * 10 + digit. For 5600 that gives results 0, 0, 6 and 65, so the leading zeros of the reversed number vanish without any special code.

    The 32-bit rule needs an explicit check. Python integers have no fixed size, so 9000000001 is a perfectly good int and nothing would stop it. The function has to compare the result with the limit itself, before adding each digit. If the next value would exceed the limit, it returns 0 at once.

    Negative numbers need a small detour. In Python, % and // round toward negative infinity, so -2408 % 10 is 2, and -2408 // 10 is -241. These are not the last digit and the digit-dropped number you want. So the function sets the sign aside, works on abs(x), and puts the sign back at the end.

    Because the number has at most 10 digits, the loop runs at most 10 times. In general, the number of digits is about the base-10 logarithm of |x|, which gives the O(log |x|) time.

    Step by step

    1. Record the sign. sign is -1 when x is negative and 1 otherwise, using a conditional expression: a if condition else b.
    2. Make x positive with abs. The digits of -2408 and 2408 are the same.
    3. Set limit. It is 2**31 - 1 for a positive answer and 2**31 for a negative one, because the 32-bit range holds one more negative number than positive ones. ** raises to a power.
    4. Start result at 0. It collects the digits.
    5. Loop while x > 0. Each pass removes one digit, so it runs once per digit.
    6. Take the last digit with x % 10. In -2408 the digits come out as 8, 0, 4, 2.
    7. Drop it from x with x //= 10. Floor division discards the remainder: 2408 // 10 is 240.
    8. Check before adding. If result * 10 + digit is greater than limit, return 0. This is the key step. For 1000000009, result reaches 900,000,000 before the last digit, and 9,000,000,001 is above the limit.
    9. Add the digit: result = result * 10 + digit.
    10. Return sign * result to put the sign back.

    The solution in Python

    class Solution:
        def reverse(self, x: int) -> int:
            sign = -1 if x < 0 else 1
            x = abs(x)
            limit = 2**31 - 1 if sign == 1 else 2**31
            result = 0
            while x > 0:
                digit = x % 10
                x //= 10
                if result * 10 + digit > limit:
                    return 0
                result = result * 10 + digit
            return sign * result
    

    Python details:

    • % and // floor toward negative infinity, which is why the code works on a non-negative x. For a positive x they give the last digit and the number without it, as expected.
    • Python integers grow as needed and never wrap, so the 32-bit limit must be enforced by the comparison. A shortcut such as int(str(x)[::-1]) returns 9000000001 for 1000000009, not 0, and it does not handle the minus sign.
    • The check runs on the value about to be stored, so an out-of-range answer is never built. The intermediate values are prefixes of the final reversed number and are never larger than it, so the first time one exceeds the limit, the whole answer would too.
    • The parameter x is reassigned inside the function. This is fine, because integers are immutable and the caller's variable is untouched.

    Complexity

    The loop runs once per digit, at most 10 times for a 32-bit input, which is O(log |x|). The function stores a few integers, so the extra space is O(1).

    Edge cases and common mistakes

    • Trailing zeros. 5600 gives 65, and 120 gives 21. No code is needed to remove the zeros.
    • Zero. 0 gives 0, since the loop never runs.
    • The ends of the range. 2147483647 and -2147483648 both reverse to numbers beyond 32 bits, so both give 0.
    • Right below the limit. 1463847412 reverses to 2147483641, which fits, so the answer is 2147483641, and -1463847412 gives -2147483641.
    • Using % on a negative number. -2408 % 10 is 2, not -8. Take the absolute value first.
    • Checking the limit after the loop. That works in Python for a small number, but the lesson's check, done before adding each digit, shows the habit that is needed in languages where a number can overflow.

    Testing

    xresult
    560065
    -2408-8042
    10000000090
    -10-1
    14638474122147483641
    21474836470
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free