Reverse Integer

Medium

Topics
Math

Given a signed 32-bit integer x, return x with its digits reversed. If reversing causes the value to fall outside the 32-bit signed range [-2^31, 2^31 - 1], return 0.

Example 1

in123
out321
Digits are read off the end with % 10 and pushed on with * 10. The real content of the problem is the 32-bit range: the check has to happen before the multiply, because detecting it afterwards means the overflow already happened.
Cells are decimal digits; the sign is kept aside and reapplied.
Input:  x = 123
Output: 321

Example 2

in123
out321
Input:  x = -123
Output: -321

Example 3

in120
out021
Input:  x = 120
Output: 21

Constraints

  • -2^31 <= x <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Peel digits off the right with %10 and push them onto a result with result*10 + digit. The only subtlety is detecting 32-bit overflow before it happens.

Approach

  1. Track the sign, work with the absolute value.
  2. Pop the last digit and append it to the running result.
  3. Before each append, check the result would not exceed the 32-bit bound; if it would, return 0.

Dry Run

n = 123
  res = 3, then 32, then 321                    in range    ->  321
n = -123
  sign is taken off first, so the digits reverse identically ->  -321
n = 1534236469
  res = 9, 96, 964, 9646, 96463, ... ending at 9646324351
  9646324351 is larger than 2^31 - 1            out of range ->  0
answer 321, then -321, then 0
Stripping the sign up front means the reversal loop only ever handles a
non-negative number, so `n % 10` and `n // 10` behave predictably -- in languages
where `%` can return a negative remainder, that is the difference between working
and not.
The range check is the real content of this problem. Python's integers are
unbounded, so the intermediate 9646324351 forms happily and a single comparison at
the end suffices. In Java, C++ or JavaScript that multiply has already overflowed
by then, which is why the check belongs BEFORE the multiply: compare against
(2^31 - 1) / 10 and reject rather than detect.
Note -2147483648 also returns 0. Its reversal exceeds the positive bound, so the
most negative input is not a special case -- it simply fails the same test.

Complexity

  • Time — O(log x): one iteration per digit.
  • Space — O(1): a couple of integer variables.

Common Pitfalls

  • In fixed-width languages, check overflow using the bound before multiplying, not after.

Full Solution — all languages

class Solution:
    def reverse(self, n):
        sign=-1 if n<0 else 1
        n=abs(n)
        res=0
        while n:
            res=res*10+n%10
            n//=10
        res*=sign
        return res if -2**31<=res<=2**31-1 else 0
SensAI
Beta
Tap the mic to stop voice mode