8. String to Integer (atoi)

8. String to Integer (atoi)

class Solution:
    def myAtoi(self, s: str) -> int:
        t=""
        space=0
        digit=0
        for v in s:
            # print(v,digit)
            if not v.isdigit() and digit:
                break
            if v in '-+1234567890':
                digit=1
                t+=v
                space=0
            elif v in ' ':
                continue
            else:
                break
        if len(t)==0:return 0
        try :
            t=int(t)
            if t < -2**31:
                return -2**31
            elif t > (2**31) - 1:
                return (2**31) - 1
            return t
        except:
            return 0

你可能感兴趣的:(leetcode)