LeetCode 8: String to Integer (atoi) (python)

来源:互联网 发布:java缓存和中间件 编辑:程序博客网 时间:2024/05/29 08:03

原题:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

思路:
题意是将字符串转换成整数,思路很简单,但有几处细节需要考虑:
1. 数字前面有空格,如s=” 123456”,空格需舍弃;
2. 数字前出现了不必要或多于的字符导致数字认证错误,输出0。如s=” b1234”,s=” ++1233”, s=” +-1121”;
3. 数字中出现了不必要的字符,返回字符前的数字。如s=” 12a1”, s=” 123 123”;
4. 数字越界,超过了范围(-2147483648–2147483647),分别返回-2147483648和2147483647。

代码:

class Solution(object):    # 判断是否字符串是否溢出int的范围,如果大于,返回2147483647;如果小于-2147483648,返回-2147483648    def Outofbounds(self, s):        if(s[0]=='-'):            if((len(s)>11)or((len(s)==11)and(s>'-2147483648'))):                return True,-2147483648            else:                return False,s        else:            if((len(s)>10)or((len(s)==10)and(s>'2147483647'))):                return True,2147483647            else:                return False,s    # 判断str是否符合要求,并排除符合要求字符串的多余项    def judge_delete(self,s):        #是否出现“+”或者“-”的flag        signflag=False        #是否出现数字的flag        numflag=False        # 除掉开头的“ ”        while(s[0]==' '):            s=s[1:]        res=""        for i in range(0,len(s)):            # 样例:"+ 122"为非法            # 样例:"++122"为非法            if((signflag)and(not(numflag))and(not((s[i]>='0')and(s[i]<='9')))):                return False,s            #压入合法“+”或者“-”            if((not(numflag))and(not(signflag))and((s[i]=='+')or(s[i]=='-'))):                signflag=True                res+=s[i]            #压入合法数字            if((s[i]>='0')and(s[i]<='9')):                numflag=True                res+=s[i]            # 样例:"a123",首字母非“+”、“-”和数字的样例非法            if(not((signflag)or(numflag))):                return False,s            # 样例:"0123aaa",排除末尾非数字的串            if((numflag)and(not((s[i]>='0')and(s[i]<='9')))):                break        # 样例:"+"或者“-”为非法        if((len(res)==1)and(signflag)):            return False,res        # 样例:"+333333333",除掉类似样例的“+”号        elif(res[0]=="+"):            res=res[1:]        return True,res    def myAtoi(self, str):        if(str==""):            return 0        try:            flag,str=self.judge_delete(str)            #非法情况直接返回0,合法情况得到精简的str            if(not(flag)):                return 0            flag,res=self.Outofbounds(str)            #判断str是否超出范围,超出范围输出2147483647、-2147483648;不超出范围转化成int,并输出其本身            if(flag):                return res            else:                return int(str)        except:            return 0
0 0
原创粉丝点击