SDE & MLE Prep

7. Reverse Integer

Problem

Reverse the digits of a 32-bit signed integer x, keeping its sign. Return 0 if the result falls outside [−2³¹, 2³¹ − 1], and assume 64-bit integers aren't available.

Example: 123 → 321; -123 → -321; 120 → 21

Pop digits with % 10 and push with * 10. Before pushing, check that the result stays within [−2³¹, 2³¹−1].

Complexity: O(log x).

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        x, res = abs(x), 0
        while x:
            x, d = divmod(x, 10)
            res = res * 10 + d
        res *= sign
        return res if -2 ** 31 <= res <= 2 ** 31 - 1 else 0