题目:String to Integer

这个问题只要考对一个问题思考的是否全面。

思路很简单:

遍历字符串将其一一转成数字,前面转化的数字乘10再加上后面转化的数字。

注意:

1.跳过前面的空格,注意不用跳过数字中间的空格。

2.考虑正负号在数字前面的情况。

2.考虑数字值过大超过int的范围的情况。这个最重要。

 1 /*****************************************************************
 2 Implement atoi to convert a string to an integer.
 3 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.
 4 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.
 5 *****************************************************************/
 6 #include<stdio.h>
 7 #include <stdlib.h>
 8 #include <ctype.h>
 9 
10 int myAtoi(char* str) {
11         int i = 0;
12         int flag = 1;//正负符号标志
13         int num = 0;
14     while(isspace(str[i]))i++;//跳过空格
15     if(str[i] == '-' || str[i] == '+'){//正负号
16         if(str[i++] == '-')flag = -1;
17     }
18     while(isdigit(str[i])){
19         if(num > 214748365){//15551646163546
20             num = -num;
21             break;
22         }
23         num = num*10 + str[i++] - '0';
24         if(num < 0)break;
25     }
26     if(flag > 0 && num < 0)num = 2147483647;
27     if(flag < 0 && num < 0){
28         num = 2147483648;//注意:这里不能写成-2147483648,会报错。因为2147483648是无符号数,不能加负号
29         //flag = 1;//可以不加这一句话
30     }
31     return num*flag;
32 }
33 
34 int main(void)
35 {
36     int n;
37     char str[] = "    -2147483649";
38     n = atoi(str);
39     printf("n=%d\n",n);
40     n = myAtoi(str);
41     printf("n=%d\n",n);
42     return 0;
43 }

最重要的是:

  如果这个数用int表示溢出了,那么,我这里是当当前的字母还是数字时,判断前9位数>214748365,则一定是负数。然后在判断10位数转化后是否为负数。

  上面28行的问题一定要注意,很容易忽略。