7. Reverse Integer

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Solution:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x >= 0:
            rev_x = int(str(x)[::-1])
        else:
            rev_x = -int(str(x)[1:][::-1])
        
        if (rev_x >= 2147483647 or rev_x <= -2147483648):
            return 0
        else:
            return rev_x

TIme Complexity:

The time complexity of this function is O(n), where n is the number of digits in the input integer x. This is because the function needs to convert the input integer to a string and reverse it, which takes O(n) time. The subsequent check to ensure the reversed integer does not exceed the 32-bit signed integer range also takes constant time.

Space Complexity:

The space complexity of this function is O(1) because the function only uses a constant amount of extra space to store variables regardless of the size of the input.