Updated-leetcode实现atoi函数,为特定输出提供错误结果

问题描述 投票:0回答:1

我的将字符串转换为整数的atoi函数的代码对于“ 3.14159”失败

问题的链接是Atoi function

INT_MIN=-2**31
INT_MAX=((2**31)-1)
class Solution:
    def myAtoi(self, s: str) -> int:
        result=0
        start=0
        flag=False
        if len(s)==0:
            return 0
        else:
            s=s.strip().split()[0] 
            if s[0]=='+' or s[0]=='-':
                start+=1
            if s[0]=='-':
                flag=True
            n=len(s)
            for i in range(start,n):
                if (ord('9')>=ord(s[i])) and (ord(s[i])>=ord('0')):
                    result = result*10 +(int(ord(s[i])-ord("0")))
                else:
                    result=result
                    #break
                print(result)
        if flag==True:
            result=-result 
        if result <INT_MIN:
            return INT_MIN
        if result >INT_MAX:
            return INT_MAX 
        return result

它输出314159但预期输出应为3。小数点后的值应舍弃。

调试器语句给了我

- 3
- 3 # the code should stop here
- 31# problem
- 314 # problem
- 3141 # problem 
- 31415 # problem
- 314159 #  problem

我尝试在else中使用break,但是IndexError:列表索引超出范围

有人可以向我建议我的代码有什么问题吗?

python python-3.x python-2.7
1个回答
0
投票

除了其他建议,您需要替换:

str=(str.lstrip()).rstrip()

with

str = str.strip().split()[0]  # don't parse beyond the first space character
© www.soinside.com 2019 - 2024. All rights reserved.