【字符串】8. 字符串转换整数 (atoi)

题目:

 

解答:

32位 最大值和最小值分别是 2147483647, -2147483648。 如果 res = 214748364,r > 7, 那么接下来的那一步操作,res = res * 10 + r = 2147483648 > INT_MAX, 直接溢出报错。不过,我不理解的地方是,为什么它不考虑负数,因为负数 是可以到达 2147483648 的。

 1 class Solution {
 2 public:
 3     int myAtoi(string str) 
 4     {
 5         if (str.size() == 0)
 6         {
 7             return 0;
 8         }
 9 
10         int i = 0;
11         int minus = 1;
12 
13         // skip spaces
14         while (str[i] == ' ')
15         {
16             i++;
17         }
18 
19         // get sign
20         if (str[i] == '-')
21         {
22             minus = -1;
23             i++;
24         }
25         else if (str[i] == '+')
26         {
27             minus = 1;
28             i++;
29         }
30 
31         // convert numbers
32         int num = 0;
33         while (isdigit(str[i]))
34         {
35             // 214748364 = INT_MAX / 10
36             if ((num == 214748364) && ((str[i] - '0') > 7) || (num > 214748364))
37             {
38                 return (minus > 0) ? INT_MAX : INT_MIN;
39             } 
40             num = 10 * num + (str[i] - '0');
41             i++;
42         }
43 
44         return (minus > 0) ? num : -num;
45     }
46 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12825745.html