题目描述
方法:
多种情况考虑
class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
i = 0
n = len(s)
sign = 1
while i<n and s[i] == " ":
i += 1
if i < n and s[i] in "+-":
if s[i] == "-":
sign = -1
i += 1
if i<n and not "0" <= s[i] <= "9" or i==n:
return 0
j = i
while j < n and "0" <= s[j] <= "9":
j += 1
res = sign*int(s[i:j])
if res < -2**31:
return -2**31
elif res>2**31-1:
return 2**31-1
else:
return res