leetcode(8) string to integer (atoi) 解法:

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.

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.

解法:

没啥好说的,输入为空格,+,- 或数字,出现 +,-后直接计数,如果已经非法则返回0.

字符串转数字的公式为:

1
2
x = int(str[i]);
result = result * 10 + x;

我的代码:

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
class :
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
i = 0;
flag = 1;
if(str == ""):
return 0;
while(str[i]==" "):
i+=1;
if(i == len(str)):
return 0;
result = 0;
if(str[i]=="-" and i!=len(str)-1):
if(str[i+1]!=" " and str[i+1] !="+" and str[i+1]!="-"):
flag = -1;
i+=1;
else:
return 0;
if(str[i]=="+"and i!=len(str)-1):
if(str[i+1]!=" " and str[i+1] !="+" and str[i+1]!="-"):
flag = 1;
i+=1;
else:
return 0;
while(ord(str[i])>=48 and ord(str[i])<=57):
x = int(str[i]);
result = result * 10 + x;
i+=1;
if(i == len(str)):
break;
if(flag == -1):
result = -result;
if(result<-2147483648):
return -2147483648;
if(result >2147483647):
return 2147483647
return result;