Python 52ms 9 line, EASY


  • 0
    F
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            #deal with inputs which have invalid characters in the middle. eg: "  -0012a42"
            for i,c in enumerate(str.strip()):
                if (not c.isdigit()) and (c not in '+-'):
                    str=str.strip()[:i]
                    break
            try:
                ret=int(str)
                return ret if -2147483648<=ret<=2147483647 else (-2147483648,2147483647)[ret>0]
            except:
                return 0
    

    try/except will deal with most invalid cases automatically


Log in to reply
 

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