Implement atoi to convert a string to an integer.
思路
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 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 if (answer > 2147483647): answer = 2147483647 elif (answer < -2147483648): answer = -2147483648 return answer
|