◀ THE GRIND — BIT MANIPULATION

Reverse Integer

MEDIUM✓ CHIP-TIMEDLC #7 — FULL STATEMENT ↗

The drill: Reverse the digits of a signed 32-bit integer — and if the flipped result would overflow that range, hand back 0 instead of the wrong number.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A signed 32-bit integer arrives, and its digits need to come back in reverse order, sign preserved, as a fresh signed integer.

If flipping the digits would push the result outside the signed 32-bit range, the correct response is to hand back 0 instead of the wrapped or overflowed value.

Trailing zeros in the original number simply disappear once reversed, since a leading zero isn't a real digit — and the sign always stays attached to the number itself, never flipping independently.

EX 01
x = 123
321
THE BOARD'S EXAMPLE
EX 02
x = -123
-321
SIGN CARRIES THROUGH THE REVERSAL
EX 03
x = 120
21
TRAILING ZERO DISAPPEARS ONCE REVERSED
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Turning the number into a string, reversing it and parsing it back gets the digits right — but that only works because the reversed value still fits somewhere your language can hold it.

HINT 2 THE STRUCTURE

Overflow has to be caught before it happens, not after — once a 32-bit value has already wrapped around, the number sitting in front of you is lying about what it represents.

HINT 3 ONE STEP FROM THE ANSWER

Build the reversed number one digit at a time; before every multiply-and-add step, check whether it would push past INT_MAX or below INT_MIN, and bail out to 0 right there.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE DIGIT POPPATTERN · DIGIT POP, OVERFLOW GUARDx = 123
1
2
3
RUNNING RESULT
result0
STEP 1

123 — peel digits off the end with %10 and //10, checking the overflow boundary before every multiply-and-add.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/reverse-integer.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def reverse(self, x: int) -> int:
        INT_MIN, INT_MAX = -2**31, 2**31 - 1
        sign = -1 if x < 0 else 1
        x = abs(x)
        result = 0
        while x:
            digit = x % 10
            x //= 10
            if result > (INT_MAX - digit) // 10:
                return 0
            result = result * 10 + digit
        result *= sign
        if result < INT_MIN or result > INT_MAX:
            return 0
        return result
TIME O(D)SPACE O(1)PYTHON · RACE PACE · 16 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED