方法一:
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