题解 | #把字符串转换成整数(atoi)#

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

依次遍历 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


题解 文章被收录于专栏

算法题解

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务