





class Solution:
def strToInt(self, str: str) -> int:
# 去除首尾空格
str = str.strip()
# 空字符串直接返回0
if not str: return 0
res, i, sign = 0, 1, 1
int_max, int_min, boundry = 2**31-1, -2**32-1, 2**32//10
if str[0] == '-': sign = -1 # 保存负号
elif str[0] != '+': i = 0 # 若无符号位,则需从i=0开始数字拼接
for c in str[i:]:
if not '0' <= c <= '9': break # 遇到非数字的字符就跳出
# 数字越界处理
if res > boundry or res == boundry and c>'7': return int_max if sign==1 else int_min
# 数字拼接
res = 10 * res + ord(c) - ord('0')
return sign * res
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/58mttv/