LeetCode-8-String-to-Integer (atoi) 细节题

来源:互联网 发布:centos下安装jdk1.8 编辑:程序博客网 时间:2024/06/07 03:24

很无聊的题目,注意一下要求的各种边界条件,仔细读题就好,不读题免不了WA几发


class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        if(str==""):return 0        Len=len(str)        flag=1        pl=0        pr=Len        for i in range(Len):            if str[i]!=" ":                if str[i]=='+':                    pl=i+1                    break                elif str[i]=='-':                    pl=i+1                    flag=-1                    break                elif str[i]>='0' and str[i]<='9':                    pl=i                    break                else:                    return 0        if not(pl<Len and str[pl]>='0' and str[pl]<='9'):            return 0        for i in range(pl,Len):            if str[i]<'0' or str[i]>'9':                pr=i;                break;        ans=flag*int(str[pl:pr])        if ans<-2147483648:            return -2147483648        if ans>2147483647:            return 2147483647        return ans