O(1) space complexity in place 6 lines Python solution


  • 3
    def reverse(self, x):
        """
        For this question, we need to handle the "overflow" case explicitly :(
        if abs(x) >= 2147483647:
            return 0
        """
    
        result = 0
        pos_x = abs(x)
        while pos_x:
            result = result * 10 + pos_x % 10
            pos_x /= 10
    
        """
        For this question, we need to handle the "overflow" case explicitly :(
        if result >= 2147483647:
            return 0
        """
        return result if x >= 0 else result * (-1)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.