############################################################ 主要问题是判断字符是否是整数用int()配合try实现,并且可用try检测特殊情况 本题最主要的还是要注意到各种特殊情况输入 ############################################################
class Solution: def myAtoi(self, str: str) -> int: p = [] #需要输出的值 test = True j = -1 for i in range(len(str)): if str[i] == " " and test == True: #排除点前面的“ ” continue else: p.append(str[i]) j = j+1 if p[0] != "-" and p[0] != "+" and test == True: #查第一个字符是不是数字 try: start = int(p[0]) test = False continue except ValueError: return 0 if (p[0] == "-" or p[0] =="+" )and test == True: #查第一个字符是不是“+”或“-” test = False continue try: #将后面的非数字字符剔除 int(p[j]) except ValueError: del (p[-1]) break try: #越界检测 k = int(''.join(p)) #并且防止出现“”,“ ”等情况 if k >=2**31-1: return 2**31-1 elif k <= -2**31: return -2**31 else: return k except ValueError: return 0