题目描述:
方法一:正则
class Solution: def myAtoi(self, str: str) -> int: return max(min(int(*re.findall(‘^[\+\-]?\d+‘, str.lstrip())), 2**31 - 1), -2**31)
方法二:
class Solution: def myAtoi(self, str: str) -> int: str = str.strip() if str == "": return 0 left = 0 right = 0 maxi=2147483647 mini=-2147483648 if str[0]=="+" or str[0]=="-": left = 1 if(left==1 and len(str)==1) or str[left]<"0" or str[right]>"9": return 0 for i in range(left,len(str)): if str[i]>=‘0‘ and str[i]<=‘9‘: right = i else: break res = str[left:right+1].lstrip("0") if len(res)==0: return 0 else : res=eval(res) if left==1 and str[0]==‘-‘:#判断正负 res=-res if res>maxi: return maxi elif res<mini: return mini else : return res
原文:https://www.cnblogs.com/oldby/p/11156160.html