leetcode-8 字符串转换整数(atoi) Python

方法一:

class Solution:
    def myAtoi(self, str: str) -> int:
        INT_MAX = 2**31 - 1
        INT_MIN = -2**31
        if not str:
            return 0
        str = str.strip()
        size = len(str)
        i = 0
        res = 0
        sign = 1 
        if i < size and (str[i] == '+' or str[i] == '-'):
            sign = 1 if str[i] == '+' else -1
            i += 1
        while i < size and (str[i] >= '0' and str[i] <= '9'):
            if res > INT_MAX // 10 or (res == INT_MAX // 10 and (ord(str[i]) - ord('0') > 7)):
                if sign == 1:
                    return INT_MAX
                else:
                    return INT_MIN
            res = res * 10 + ord(str[i]) - ord('0')
            i += 1
        return res * sign```
方法二:自动机

```python
INT_MAX = 2 ** 31 - 1 
INT_MIN = -2 ** 31
class Automaton:
    def __init__(self):
        self.state = 'start'
        self.sign = 1
        self.ans = 0
        self.table = {
            'start': ['start', 'signed', 'in_number', 'end'],
            'signed':['end', 'end', 'in_number', 'end'],
            'in_number':['end', 'end', 'in_number', 'end'],
            'end': ['end', 'end', 'end', 'end']
        }
    def get_col(self, c):
        if c.isspace():
            return 0
        if c == '+' or c == '-':
            return 1
        if c.isdigit():
            return 2
        return 3
    def get(self, c):
        self.state = self.table[self.state][self.get_col(c)]
        if self.state == 'in_number':
            self.ans = self.ans * 10 + int(c)
            self.ans = min(self.ans, INT_MAX) if self.sign == 1 else min(self.ans, -INT_MIN)
        elif self.state == 'signed':
            self.sign = 1 if c == '+' else -1


class Solution:
    def myAtoi(self, str: str) -> int:
        automation = Automaton()
        for c in str:
            automation.get(c)
        return automation.sign * automation.ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值