剑指offer-把字符串转换成整数(python)

思路:不用考虑小数点,eE,额外考虑溢出。
注意一下num.index的用法

class Solution:
    def StrToInt(self, s):
        # write code here
        if not s:
            return 0
        label=1
        res=0
        numlist=['0','1','2','3','4','5','6','7','8','9']
        
        for i in s:
            if i=='+':
                label=1
            if i=='-':
                label=-1
            if i in numlist:    
                    res=10*res+numlist.index(i)
            if i not in numlist and i not in "+-":
                return 0
        if res*(label)>=2147483648 or res*(label)<=-2147483649:
            return 0
        return res*(label)

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104476124