Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Reverse Integer

MEDIUM✓ CHIP-TIMEDLC #7 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • the input is a signed integer within the standard 32-bit range
  • the output must also fit the signed 32-bit range, or the answer is 0
  • the sign of the input carries through unchanged to the output
  • leading zeros produced by the reversal are simply dropped
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 hintstake 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 boardthe pattern, step by step

THE DIGIT POPPATTERN · DIGIT POP, OVERFLOW GUARDx = 123
1
2
3
RUNNING RESULT
result → 0
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 splitstwo paces, two languages

grind/reverse-integer.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED