[LeetCode Python3] 8. String to Integer (atoi)

本文提供了两种使用Python实现字符串到整数(int)转换的方法。通过详细的代码示例,讲解了如何处理符号、非法字符及整数溢出等问题。

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

Python3 solution1:

class Solution:
    def myAtoi(self, str: str) -> int:
        strs = str.strip().split()
        if len(strs) == 0:
            return 0
        str0 = strs[0]
        index = 0
        if str0[0] == "-":
            index += 1
            while index < len(str0) and (ord(str0[index]) >= 48 and ord(str0[index]) <= 57):
                index += 1
            if index == 1:
                return 0
            res = int(str0[1:index])
            if res > 2147483648:
                return -2147483648
            else:
                return -res
        elif str0[0] == "+":
            index += 1
            while index < len(str0) and (ord(str0[index]) >= 48 and ord(str0[index]) <= 57):
                index += 1
            if index == 1:
                return 0
            res = int(str0[1:index])
            if res > 2147483647:
                return 2147483647
            else:
                return res
        elif (ord(str0[index]) >= 48 and ord(str0[index]) <= 57):
            while index < len(str0) and (ord(str0[index]) >= 48 and ord(str0[index]) <= 57):
                index += 1
            res = int(str0[0:index])
            if res > 2147483647:
                return 2147483647
            else:
                return res
        else:
            return 0

Python3 solution2:

class Solution:
    def myAtoi(self, str: str) -> int:
        index = 0
        sign = 1
        result = 0
        INT_MAX = 2147483647
        if len(str) == 0:
            return 0
        while index < len(str) and str[index] == " ":
            index += 1
        if index < len(str) and (str[index] == "-" or str[index] == "+"):
            if str[index] == "-":
                sign = -1
            index += 1
        while index < len(str) and  ord(str[index]) >= 48 and ord(str[index]) <= 57:
            if ((result > (INT_MAX // 10)) or ((result == (INT_MAX // 10)) and ((ord(str[index]) - 48) > (INT_MAX % 10)))):
                return 2147483647 if sign == 1 else -2147483648
            result = result * 10 + (ord(str[index]) - 48)
            index += 1
        return result * sign
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值