8. 字符串转换整数 (atoi)

题目

没什么好说的,注意各种情况,识别到数字之后就一直要是数字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
def myAtoi(self, str: str) -> int:
p = ''
str = str.lstrip()
n = ''
min_int = -2**31
max_int = 2**31-1
isnumeric = False
for x in str:
if not isnumeric and x == '-':
p = '-'
isnumeric = True
continue
if not isnumeric and x == '+':
isnumeric = True
continue
if x.isnumeric():
n += x
isnumeric = True
else:
break
if not n:
return 0
if int(n) > max_int:
if p:
return min_int
else:
return max_int
p += n
return int(p)
# 32 ms 13.6 MB