Python Solution with Overflow Check (52 ms)


  • 0
    S

    Steps

    1. convert int to str

    2. remove negative sign

    3. reverse string

    4. handle overflow condition
      compare lexicographically

    5. append negative sign

    class Solution(object):
        def reverse(self, x):
            '''
            :type x: int
            :rtype: int
            '''
            if x == 0: return 0
            
            # convert int to str
            s = str(x)
    
            # remove negative sign
            if x < 0:
                s = s[1:]
    
            # reverse string
            s = s[::-1]
    
            # overflow condition
            limit = str(2**31)
            if len(s) == len(limit):
                # compare lexicographically
                if s > limit:
                    return 0
    
            # append negative sign 
            if x < 0:
                s = '-' + s
    
            return int(s)
    

Log in to reply
 

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