这个题是写一个atoi函数,考虑的情况有点多。题目要求里面讲了输入一个字符串,从它的第一个非空格的字符开始如果是一个合法的数字,就把它打印出来,忽略这个数字后面的其它字符。

如果开始的空格之后构不成数字,则打印0。如果超出了int的范围,则打印INT_MAX或者INT_MIN。

这是一个easy的题目,只要考虑清楚所有情况就没有问题了。

++
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
class Solution {
public:
int myAtoi(string str) {
int i = 0;
int symbol = 0;
int start = 0, end = 0;
long long int_max = 2147483647;
long long int_min = -2147483648;
long long ans = 0;
while(str[i] != '\0'){
if(str[i]-'0'>=0 && str[i]-'0'<10){
if(start){
ans = ans*10+(str[i]-'0');
if(ans > int_max){
if(symbol == 2) return int_min;
else return int_max;
}
}else{
if(symbol == 0){
start = 1;
ans = str[i]-'0';
}else{
return 0;
}
}
end = 1;
}
else if(!start && (str[i]=='+' || str[i]=='-')){
start = 1;
if(str[i]=='-') symbol = 2;
else symbol = 1;
}
else{
if(end){
if(symbol==2) ans = -ans;
}
if(str[i] == ' ' && !start){
i++; continue;
}
return ans;
}
i++;
}
if(!start) return 0;
if(symbol==2) ans = -ans;
return ans;
}
};