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.

spoilers alert... click to show requirements for atoi.

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.

思路:

思路比较简单,认真即可。
代码:

 1     int atoi(const char *str) {
 2         while(*str == ' ')
 3             str++;
 4         int param = 1;
 5         if(*str == '+')
 6             str++;
 7         else if(*str == '-'){
 8             str++;
 9             param = -1;
10         }
11         else if(*str < '0' || *str > '9')
12             return 0;
13         while(*str == '0')
14             str++;
15         const char *tmp = str;
16         while(*tmp >= '0' && *tmp <= '9')
17             tmp++;
18         if(tmp - str > 10){
19             if(param > 0)
20                 return INT_MAX;
21             return INT_MIN;
22         }
23         else if(tmp - str == 10){
24             string max = "2147483647";
25             int i = 0;
26             for(const char *t = str; t < tmp; t++, i++){
27                 if(*t > max[i]){
28                     return param > 0 ? INT_MAX : INT_MIN;
29                 }
30                 else if(*t < max[i])
31                     break;
32             }
33             if(i == 10)
34                 return param > 0 ? INT_MAX : INT_MIN + 1;
35         }
36         int result = 0;
37         for(const char *t = str; t < tmp; t++){
38             result = result * 10 + (*t - '0');
39         }
40         return param*result;
41     }
原文地址:https://www.cnblogs.com/waruzhi/p/3457651.html