Sunday, January 6, 2013

[LeetCode] 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.
» Solve this problem


[解题思路]
实现细节题。注意几个测试用例:
1. 不规则输入,但是有效
"-3924x8fc", "  +  413",
2. 无效格式
 " ++c", " ++1"
3. 溢出数据
"2147483648"

[Code]
Update: refactor some logic and shrink the code from 38 lines to 21 lines. (3/5/2013)
1:       int atoi(const char *str) {  
2:            int num=0;  
3:            int sign =1;  
4:            int len = strlen(str);  
5:            int i =0;  
6:            while(str[i] == ' ' && i< len) i++;  
7:            if(str[i] == '+') i++;  
8:            if(str[i] == '-') {sign = -1; i++;}  
9:            for(;i<len; i++)  
10:            {  
11:                 if(str[i] == ' ') break;  
12:                 if(str[i]<'0' || str[i] > '9') break;  
13:                 if(INT_MAX/10 < num || INT_MAX/10 == num && INT_MAX%10 < (str[i] -'0'))  
14:                 {  
15:                      return sign == -1 ? INT_MIN : INT_MAX;  
16:                      break;  
17:                 }  
18:                 num = num*10 + str[i] -'0';  
19:            }  
20:            return num*sign;  
21:       }  


No comments:

Post a Comment