8,字符串转换整数(atoi)

class Solution:
    def myAtoi(self, str: str) -> int:
        symbol = ""
        rlt = ""
        str = str.lstrip()
        if not str:
            return 0
        if str[0] == "-":
            symbol = "-"
            str = str[1:]
        elif str[0] == "+":
            str = str[1:]
        for i in str:
            if i.isdigit():
                rlt += i
            else:
                break
        try:
            rlt = symbol + rlt
            int_rlt = int(rlt)
            if int_rlt < -2**31:
                int_rlt = -2**31
            elif int_rlt > 2**31-1:
                int_rlt = 2**31-1
            return int_rlt
        except Exception:
            return 0

猜你喜欢

转载自blog.csdn.net/weixin_42758299/article/details/88533008