Wednesday, June 4, 2014

String to integer (atoi) -- Leetcode

Question:

Answer:
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.
some test cases:
1. 不规则输入,但是有效
"-3924x8fc", "  +  413",
2. 无效格式
 " ++c", " ++1"
3. 溢出数据
"2147483648", "214748365"
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