依次遍历 s 的每个字符,根据要求求解,当首字母是 "+-" 时,影响数字符号,其他情况判断字符是否为 "0-9",然后将数字拼接起来,最终判断结果是否超过范围
class Solution:
    def StrToInt(self , s: str) -> int:
        # write code here
        res = 0
        flag = True
        for i, c in enumerate(s.strip()):
            if i == 0:
                if c == "-":
                    flag = False
                elif c == "+":
                    continue
                elif "0" <= c <= "9":
                    res = res * 10 + int(c)
                else:
                    break
            else:
                if "0" <= c <= "9":
                    res = res * 10 + int(c)
                else:
                    break
        if not flag:
            res = -res
        if res < - 2 ** 31:
            res = - 2 ** 31
        elif res > 2 ** 31 - 1:
            res = 2 ** 31 - 1
        return res