Problem Statement in English

You’re given a signed 32-bit integer x. You need to reverse the digits of x and return the reversed integer. If reversing x causes the value to go outside the signed 32-bit integer range [$-2^31$, $2^{31} - 1$], then return 0.


Approach

We can convert the integer to a string, reverse the string, and then convert it back to an integer. We also need to handle the sign of the integer and check if the reversed integer is within the 32-bit signed integer range.

And we’re done!


Solution in Python


class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        if x < 0:
            res = int(str(x)[1:][::-1]) * -1
        else:
            res = int(str(x)[::-1])
        
        if res > pow(2, 31) - 1 or res < pow(-2, 31):
            return 0
        
        return res

Complexity

  • Time: $O(n)$
    where $n$ is the number of digits in the integer.

  • Space: $O(1)$
    Since we are not using any extra space that scales with the input size, the space complexity is constant.


And we are done.