题目

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Python

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:
def myAtoi(self, str):
if str == "":
return 0
for i in range(0, len(str)):
if str[i] != ' ':
str = str[i:]
break
if str in ('-', '+'):
return 0
sign = 1
if str[0] == '-':
sign = -1
str = str[1:]
elif str[0] == '+':
str = str[1:]
if ord(str[0]) > ord('9') or ord(str[0]) < ord('0'):
return 0
r = 0
for i in str:
if ord(i) > ord('9') or ord(i) < ord('0'):
break
else:
r = r*10 + int(i)
r = r*sign
if r > 2147483647:
return 2147483647
elif r < -2147483648:
return -2147483648
return r