8. String to Integer (Atoi)

题目

1
2
3
4
5
6
7
8
9
10
Implement atoi to convert a string to an integer.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

题目分析

实现目标

对与一个数值类型的字符串(比如121212121,-12121212),能转化成int类型的数值

要处理的情况(case)

  • 忽略开头的空格
  • 若中间有非法字符,则忽略该字符即之后的所有字符
  • 如果值大于2147483647 则返回2147483647,如果值小于-2147483648则返回-2147483648,简单讲就是值最大为2147483647,最小为-2147483648

测试数据

1
2
3
4
5
6
7
8
input              |        output
"-2147483649" | "-2147483648"
"-2147483648" | "-2147483648"
" 2147483649" | " 2147483647"
" 2147x83649" | " 2147"
" +-21474836" | " 0"
" 21474 3649" | " 21474"
"214743336493" | " 2147483647"

代码

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
class Solution(object):
def myAtoi(self, str1):
"""
:type str: str
:rtype: int
"""
sign = 1
base = 0
head = 1
for x in str1:
if x == ' ' and head == 1:
continue
elif (x == '-' or x == '+') and head==1:
sign = 1 - 2 * (x == '-')
head = 0
elif x >= '0' and x <= '9':
head = 0
if base*sign > 2147483647:
return 2147483647
elif base*sign <= -2147483648:
return -2147483648
base = base * 10 + ord(x) - ord('0')
else:
if base < 2147483648:
return base * sign
elif sign == -1:
return -2147483648
elif sign == 1:
return 2147483647
if base < 2147483648:
return base * sign
elif sign == -1:
return -2147483648
elif sign == 1:
return 2147483647

本文标题:8. String to Integer (Atoi)

文章作者:定。

发布时间:2017年7月9日 - 16时07分

本文字数:1,754字

原始链接:http://cocofe.cn/2017/07/09/String to Integer(OJ)/

许可协议: Attribution-NonCommercial 4.0

转载请保留以上信息。