Leetcode 8 String to Integer(atoi)

实现 atoi,将字符串转为整数。
该函数首先根据需要丢弃任意多的空格字符,直到找到第一个非空格字符为止。如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

字符串可以在形成整数的字符后面包括多余的字符,这些字符可以被忽略,它们对于函数没有影响。
当字符串中的第一个非空字符序列不是个有效的整数;或字符串为空;或字符串仅包含空白字符时,则不进行转换。
若函数不能执行有效的转换,返回 0。

说明:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。如果数值超过可表示的范围,则返回 INT_MAX (2^31 − 1) 或 INT_MIN (−2^31) 。

Example 1:
Input: “42”
Output: 42

Example 2:
Input: “ -42”
Output: -42
Explanation: The first non-whitespace character is ‘-‘, which is the minus sign.Then take as many numerical digits as possible, which gets 42.

Example 3:
Input: “4193 with words”
Output: 4193
Explanation: Conversion stops at digit ‘3’ as the next character is not a numerical digit.

Example 4:
Input: “words and 987”
Output: 0
Explanation: The first non-whitespace character is ‘w’, which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:
Input: “-91283472332”
Output: -2147483648
Explanation: The number “-91283472332” is out of the range of a 32-bit signed integer.Thefore INT_MIN (−231) is returned.

感慨:
第一次做的时候还是个小白,当时这道题真把我人都气傻了,不过现在再做一遍的时候发现也不过如此,或许这就是膨胀吧。
不过!!!我总觉得test case少了很多啊,我记得以前有什么1e5 = 10^5之类的样例啊,这次为什么返回1啊!

题意分析:
一道需要考虑特别多特殊case的问题,例如:

  1. 是否以多个空格开头
  2. 除去空格后是否以符号开头
  3. 第一段数字是否合法
  4. 转换出来的数字是否溢出

思路分析:
这个时候不得不说python这门语言的优势了,集成了特别多好用以及通用的函数,打个比方,python中的int()函数,是不会出现因为里面的数过大而溢出的情况的。

这道题的关键就是借用try,except结构,将所有的不规则case全部一并处理。
首先将字符串左边的空格消去。
然后开始遍历首部的字符,满足终止条件则break
终止条件包括:

  1. 除首位以外的位置出现’+-‘符号
  2. 出现非数字字符

将获得的数进行int强制转换,判断其是否溢出
其余情况一概返回0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 36ms, beats 94.23%
class Solution(object):
def myAtoi(self, s):
s = s.strip()
try:
val = ''
for i in range(len(s)):
if (s[i] in '+-' and i == 0) or '0' <= s[i] <= '9':
val += s[i]
else: break
val = int(val)
if val < -2**31: return -2**31
if val > 2**31-1: return 2**31-1
return val
except:
return 0