Python Clean Soln


  • 0
    V
    import re
    
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            if not str:
                return 0
                
            str = str.strip()
            pos = 0
            sign = 1
            if str[pos] == '-':
                sign = -1
                pos += 1
            elif str[pos] == '+':
                pos += 1
            
            ret = 0
            while pos < len(str) and not re.match("\s+", str[pos]):
                if re.match("[^0-9]", str[pos]):
                    break
                digit = ord(str[pos]) - ord('0')
                if ret > 214748364 or (ret == 214748364 and digit > 7):
                    return (2147483647 if sign == 1 else -2147483648)
                    
                ret = (ret * 10) + digit
                pos += 1
                
            return ret * sign
    

Log in to reply
 

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