LeetCode 7 – Python 3 (Week 5 – 03)

Solution 1

The integers within the 32-bit signed integer range: [−231,  231 − 1].

class Solution:
    def reverse(self, x: int) -> int:
        
        ans = 0
        while x > 0:
            ans = ans * 10 + x % 10
            x = int(x / 10)
            
        if x < 0:
            x = - x
            while x:
                ans = ans * 10 + x % 10
                x = int(x / 10)
            ans = - ans
            
        return ans if -2**31<=ans<=2**31-1 else 0

Time complexity is O(logx). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started