Reverse Integer

MediumMathLeetCode 7 ↗World 8-15
0:00 / 0:00

Reverse the digits of a 32-bit integer. Pop the last digit, push it onto the result, and check for overflow before each push.

▼

The problem

LeetCode 7 (Medium). You get a signed 32-bit integer x; return it with its digits reversed. If the reversed value falls outside the 32-bit signed range [−2³¹, 2³¹ − 1], return 0. Assume the environment can't store 64-bit integers.

Examples: 123 → 321; −123 → −321; 120 → 21; 1534236469 → 0 (9646324351 is over 2,147,483,647).

TRY IT ON LEETCODE ▶

The solution

LIMIT = (2**31 - 1) // 10   # 214748364

def reverse(x):
    sign = -1 if x < 0 else 1
    x, rev = abs(x), 0
    while x:
        digit = x % 10
        x //= 10
        if rev > LIMIT or (rev == LIMIT and digit > 7):
            return 0
        rev = rev * 10 + digit
    return sign * rev

Transcript

Reverse Integer. You get a signed thirty-two bit integer, x. Reverse its digits. If the result falls outside the thirty-two bit range, return zero. And you can't store sixty-four bit numbers.

One twenty-three becomes three twenty-one. Minus one twenty-three becomes minus three twenty-one. One twenty becomes twenty-one: the leading zero falls away. But one five three four two three six four six nine, reversed, is over nine billion. Too big, so zero.

The easy way: flip x as a string, convert it back, then check the range. But the flipped number may need more than thirty-two bits. In real thirty-two bit math, it overflows before you can check it.

So build the answer one digit at a time, like an odometer. Pop the last digit: x mod ten, then divide x by ten. Push it: rev times ten, plus the digit.

Watch one twenty-three. Pop three: rev is three. Pop two: thirty, plus two, is thirty-two. Pop one: three twenty-one. A negative x? Set the sign aside, reverse the absolute value, and put the sign back.

The danger is the push: times ten can overflow. So check first, against the limit over ten: about two hundred fourteen million. If rev is above it, return zero. If rev equals it, the digit can't exceed seven: the maximum ends in seven.

In code: save the sign, take the absolute value, and while x isn't zero, pop, guard, push. Return sign times rev.

Now the big one. Pop nine: rev is nine. Pop six: ninety-six. Then four, six, three, and on, until rev is about nine hundred sixty-four million. One digit is left, but rev is above the limit over ten, so the guard trips before the push. Return zero.

Each pass removes one digit, and x has at most ten. So time is order log x, and space is order one.

Pop a digit, check the guard, push it on. That's Reverse Integer.