Problem statement

https://leetcode.com/problems/reverse-integer/

Solution

Be careful with border cases, in python you can go to string, invert, then go back.

Complexity

Complexity is $O(\log n)$, both time and space.

Code

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

If this is not allowed, use idea of stack, where we divide number by 10 and put this as new digit to new number. Time and space complexity is also $O(\log n)$.

class Solution:
    def reverse(self, x):
        sign = -1 if x < 0 else 1
        x, n = abs(x), 0
        
        while x > 0:
            n = (n * 10) + (x % 10)
            x = x // 10
            
        return 0 if n > 0x7FFFFFFF else n*sign