LeetCode-8. String to Integer (atoi)

来源:互联网 发布:淘宝订单号在哪里找 编辑:程序博客网 时间:2024/05/20 00:10

第一次感受到了编程的不容易。。。


8.

String to Integer (atoi)

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

这道题看起来不难,不过没有对异常进行解释,比如遇到字母是中断还是跳过,超过范围返回0还是最接近的值,等等等等,所以我只能先写着,然后面向测试数据编程。。
啊,第一次理解了程序员面对不清楚的需求时的感受,不但要从测试数据里的正确答案里连蒙带猜来的得知怎么对一种异常怎么处理,我还要想怎么实现啊。。。巨难受


解就不解释了,很简单的,这道题的难点只是在于处理异常而已,直接放代码了

class Solution(object):    def isLegal(self,s,index):        s=s[index:index+1]        if s=="0" or s=="1" or s=="2" or s=="3" or s=="4" or s=="5" or s=="6" or s=="7" or s=="8" or s=="9" or s==" " or s=="-" or s=="+":            return True        else:            return False    def singleStrToInt(self,s):        if s=="1":            return 1        if s=="2":            return 2        if s=="3":            return 3        if s=="4":            return 4        if s=="5":            return 5        if s=="6":            return 6        if s=="7":            return 7        if s=="8":            return 8        if s=="9":            return 9        if s=="0":            return 0    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        start=False        flag=0        ans=0        negative=False        i=0        while self.isLegal(str,i) and i<len(str):            if str[i:i+1]=="-" and not start:                negative=True                i+=1                flag+=1                start=True                continue            elif str[i:i+1]=="-" and start:                break            if str[i:i+1]=="+" and not start:                i+=1                flag+=1                start=True                continue            elif str[i:i+1]=="+" and start:                break            if str[i:i+1]==" " and not start:                i+=1                continue            elif str[i:i+1]==" " and start:                break            if flag>1:                return 0            ans*=10            ans+=self.singleStrToInt(str[i:i+1])            i+=1            start=True        if negative:            ans=-ans        if ans>2147483647:            ans=2147483647        elif ans<-2147483648:            ans=-2147483648        return ans

Your runtime beats 9.14% of python submissions

啧。

0 0
原创粉丝点击