Reverse Integer – Solution & Complexity

Solution Walkthrough

  1. Step 1: Separate sign from magnitude

    • Record whether x is negative, then work with the absolute value so digit extraction is uniform.
    • Reversing the digits of the magnitude and reapplying the sign at the end keeps the logic simple.
    • Trailing zeros vanish automatically because a leading zero in the reversed number carries no value.
  2. Step 2: Peel digits off with mod and divide

    • Repeatedly take n % 10 to read the last digit and n // 10 to drop it.
    • Build the reversed value as rev = rev * 10 + digit.
    • Stop when n reaches zero.
  3. Step 3: Guard the 32-bit range

    • After reapplying the sign, check whether the result falls outside [-2147483648, 2147483647].
    • If it does, return 0.
    • With only 32-bit arithmetic you would instead check, before each rev * 10 + digit, whether rev already exceeds 2147483647 / 10.
  4. Step 4: Reference solution

    • Extract digits from the magnitude, reverse, reapply the sign, and clamp to zero on overflow.
    • Time is O(log10(x)) (the digit count); space is O(1).
    def reverse(x: int) -> int:
        sign = -1 if x < 0 else 1
        n = abs(x)
        rev = 0
        while n > 0:
            rev = rev * 10 + n % 10
            n //= 10
        rev *= sign
        if rev < -2147483648 or rev > 2147483647:
            return 0
        return rev
  5. Step 5: Common mistakes

    • Forgetting the overflow check and returning a value outside the 32-bit range.
    • Mishandling negative mod/division semantics in languages where % keeps the dividend's sign.
    • Dropping the sign, so -123 reverses to 321 instead of -321.

FAQ