LeetCode#8 Python解

博主分享了在LeetCode第8题中使用Python解题的经历,通过暴力求解方法,逐步解决特殊情况并进行调试。文章强调了自我设计测试用例在考试中的重要性,同时提到学到的字符串组成判断技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述在这里插入图片描述在这里插入图片描述
我的解法,还是一如既往的暴力

特殊情况太多了,如果不是一次次提交之后出现通不过的测试点,我是不可能完成这道题的,但是很多考试是需要自己设计测试用例的,那我就不能做对这一道题。。。

class Solution:
    def myAtoi(self, str: str) -> int:
        if str == "" or str.isspace() == True or (len(str) == 1 and str.isdigit() == False):
            return 0

        res = ''
        for i in str:
            if i == ' ':
                continue
            elif i.isalpha() == True:
                return 0
            elif i == '+' or i == '-':
                res = i
                for j in str[str.index(i)+1:]:
                    if j.isdigit() == True:
                        res += j
                    else:
                        break
                if res == '+' or res == '-':
                    res = 0
                break
            elif i.isdigit() == True:
                res = i
                #print(str[str.index(i)+1:])
                for j in str[str.index(i)+1:]:
                    if j.isdigit() == True:
                        res += j
                    else:
                        break
                break
            return 0
        intRes = int(res)
        if intRes > 2**31-1:intRes = 2**31-1
        elif intRes < -(2**31):intRes = -2**31
        return intRes

调半天!

今天学到了怎么判断字符串是由什么组成,

str.isdigit() # True:str全由数字组成
str.isalpha() #全字母
str.isalnum() #仅字母+数字
str.isspace() #全空格
...
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值