Python solution (68ms runtime)


  • 0
    F

    class Solution(object):
    def reverse(self, n):
    """
    :type n: int
    :rtype: int
    """

        if ((n < 10) and (n > -10)):
            return n
    
        n = list(str(n))
        neg = False
        if (n[0] == "-"):
            neg = True
            n = n[1:]
    
        l = len(n)
        ptr = 0
    
        while (ptr <= (l-1)/2):
            #flip half of the string
            n[ptr],n[-(ptr+1)] = n[-(ptr+1)],n[ptr]
            ptr += 1
    
        if neg:
            n = "-" + "".join(n)
        else:
            n = "".join(n)
            
        n = int(n)
        #plug in stupid caveats about integers...
        if ((n > 2147483647) or (n < -2147483647)):
            return 0
    
        return n

Log in to reply
 

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