题目描述:
- 开头要是非空格字符,用str.strip()函数
- 只有数字不要多余的字符,用正则表达
代码:
1 import re 2 def myAtoi(str: str) -> int: 3 r = re.findall("^[+-]?d+$",str.strip()) 4 if r: 5 num = int(r[0]) 6 #防止整数溢出 7 return max(num, -2**31) if num < 0 else min(num, 2**31-1) 8 else: 9 return 0
正则表达式 参考链接:
https://deerchao.cn/tutorials/regex/regex.htm
https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/regular-expressions