L1 · FoundationsNumbers & loops~4 min · 5 tests

Reverse the Digits of an Integer

Reverse an integer's digits arithmetically, so 1234 becomes 4321 and -120 becomes -21, without converting to a string. Python interview basics, run live.

The problem

Return n with its digits reversed, keeping the sign. Trailing zeros disappear: -120 → -21. Use arithmetic, not strings.

Examples

  1. Example 1

    Input

    reverse_int(1234)

    Expected output

    4321
  2. Example 2

    Input

    reverse_int(-120)

    Expected output

    -21

+ 3 hidden tests on Submit.

Edge cases to ask about

  • Negative numbers
  • Trailing zeros
  • Zero

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · reverse_int
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Pop and push digitsO(log n)O(1)rev = rev * 10 + n % 10
    Walkthrough of the optimal approach (try it yourself first)

    Peel the last digit off n and push it onto rev with rev = rev * 10 + digit. Work on abs(n) because Python's % with negatives returns a positive remainder (-7 % 10 == 3), then reapply the sign.

    Complexity: O(log n) time, O(1) space. One iteration per digit.

    Reveal the reference solution
    def reverse_int(n):
        sign = -1 if n < 0 else 1
        n = abs(n)
        rev = 0
        while n:
            rev = rev * 10 + n % 10
            n //= 10
        return sign * rev

    Follow-ups interviewers ask

    • Return 0 if the result overflows 32 bits (LeetCode 7).

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Reverse the Digits of an Integer in Python?

    The optimal solution runs in O(log n) time and O(1) auxiliary space. One iteration per digit.

    What follow-up questions do interviewers ask about Reverse the Digits of an Integer?

    Return 0 if the result overflows 32 bits (LeetCode 7).