Implement atoi to convert a string to an integer.

思路

atoi函数的主要功能就是将字符串转换成整数,题目给出了提示,需要我们考虑清楚所有可能的情况。

百密必有一疏,在我写完代码第一次运行的时候,还是漏掉了以下三项:

  1. 应当去掉尽可能多的空格;
  2. 字符串起始可以含有+号,并将此数视为正数;
  3. 在数字之后应当可以包含任何字符。
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
symbols = ["+","-"]
numbers = ["0","1","2","3","4","5","6","7","8","9"]
length = len(str)
symbol = "+"
if (length == 0):
return 0
res = []
cur = 0
# 去除一开始的空格
while (str[cur] == " "):
cur += 1
# 判断第一个字符是不是所期待的字符
if ( (str[cur] not in symbols) and (str[cur] not in numbers) ):
return 0
else:
# 是符号的话,就存起来;否则开始转换成数字
if (str[cur] in symbols):
symbol = str[cur]
else:
res.append(str[cur])
cur += 1
# 注意到数字之后还能有别的乱七八糟的符号
for i in range(cur, length):
if (str[i] not in numbers):
break
else:
res.append(str[i])
# 处理转换数字的操作
reslen = len(res)
if (reslen <= 0):
return 0
else:
answer = 0
count = 0
for i in res[::-1]:
answer += 10 ** count * int(i)
count += 1
if (symbol == "-"):
answer = -answer
# 注意数字不能越界,python的整数范围比int的值要大
if (answer > 2147483647):
answer = 2147483647
elif (answer < -2147483648):
answer = -2147483648
return answer