mycode  98.26%

易错点: while循环式,and判断的地方先判断下标会不会超出范围

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()
        if not str :
            return 0
        res , start = '' , 0
        if str[0] == '-' or str[0] == '+' :
            res = str[0]
            start = 1 
        if start >= len(str) or not str[start].isnumeric() :
            return 0
        while start < len(str) and str[start].isnumeric():
            res += str[start]
            start += 1
        res = int(res) 
        if res > 2147483647 :
            res = 2147483647 
        elif res <  -2147483648:
            res = -2147483648
        return res
        

 

参考

思路:哪些情况下可以直接返回0呢 1) 空 2)+-符号不是开头3) 遍历到的字符不是空格、+-、数字

 def myAtoi(self, S):
        """
        :type str: str
        :rtype: int
        """
        res = ''
        
        S1 = S.strip() # need to know
        
        for s in S1:   
            if s == '': continue
            if res != '' and s in '+-': break   
            if s in '-+0123456789':  # need to know
                res += s
            else:
                break
           
        if res == '' or res == '+' or res== '-': 
            return 0
        elif int(res) < -2**31: 
            return -2**31
        elif int(res) > (2**31)-1:
            return (2**31) -1
        else: 
            return int(res)