class Solution:
def myAtoi(self, str: str) -> int:
def isdigit(c):
return c >= '0' and c <= '9'
def isspace(c):
return c == ' '
s = str.strip()
if len(s) == 0:
return 0
start = end = 0
i = 0
if s[0] == '-' or s[0] == '+':
start = end = 1
i = 1
elif not isdigit(s[0]):
return 0
while i < len(s):
if not isdigit(s[i]):
end = i
break
else:
i += 1
else:
end = i
if start == end:
return 0
nums = int(s[start:end])
if s[0] == '-':
nums = -nums
if nums < -0x80000000:
nums = -0x80000000
elif nums > 0x7fffffff:
nums = 0x7fffffff
return nums
https://leetcode-cn.com/problems/string-to-integer-atoi/
解法一
捏着鼻子先写下第一版解答
思路很简单: