leetcode 8. 字符串转换整数 (atoi)
解题思路
执行用时28ms。
思考和尝试每一种情况,每一个if
判断都会返回一个结果。
代码
class Solution:
def myAtoi(self, str: str) -> int:
str = str.strip()
length = len(str)
if length == 0:
return 0
if length == 1 and not str[0].isdigit():
return 0
if str.isdigit():
str = int(str)
if str > 2147483647:
return 2147483647
return str
if str.startswith('-') or str.startswith('+'):
i = 1
while i < length:
if not str[i].isdigit():
break
i += 1
str = str[:i]
if len(str) == 1:
return 0
else:
str = int(str)
if str > 2147483647:
return 2147483647
elif str < -2147483648:
return -2147483648
return str
if not str[0].isdigit():
return 0
if str[0].isdigit():
i = 0
while i < length:
if not str[i].isdigit():
break
i += 1
str = int(str[:i])
if str > 2147483647:
return 2147483647
elif str < -2147483648:
return -2147483648
return str