classSolution:defmyAtoi(self,str):"""
:type str: str
:rtype: int
"""
s =str.strip()
syb =1
ptr =0
res =0iflen(s)==0:return0if s[0]=='-':
syb =-1
s = s[1:]elif s[0]=='+':
s = s[1:]iflen(s)==0:return0while s[ptr].isnumeric():
res = res *10+int(s[ptr])
ptr +=1if ptr >=len(s):break
res = res * syb
if res >2147483647:
res =2147483647elif res <-2147483648:
res =-2147483648return res
正则表达式
classSolution:defmyAtoi(self,str):"""
:type str: str
:rtype: int
"""import re
pattern = r"[\s]*[+-]?[\d]+"
match = re.match(pattern,str)if match:
res =int(match.group(0))if res >2**31-1:
res =2**31-1if res <-2**31:
res =-2**31else:
res =0return res