Notes:

INT_MAX's fabs is one less than INT_MIN's fabs.

So when we use INT_MAX as the index. We need to use <= for line 11.

 1 class Solution {
 2 public:
 3     int atoi(string str) {
 4         int len = str.size(), start = 0, sign = 1, result = 0;
 5         while (str[start] == ' ') start++;
 6         if (str[start] == '+' || str[start] == '-') {
 7             sign = str[start++] == '-' ? -1 : 1;
 8         }
 9         while (start < len) {
10             if (str[start] <= '9' && str[start] >= '0') {
11                 if (result <= (INT_MAX - int(str[start] - '0'))/10) {
12                     result = result*10 + int(str[start] - '0');
13                 } else return sign > 0 ? INT_MAX : INT_MIN;
14             } else break;
15             start++;
16         }
17         return sign > 0 ? result : -result;
18     }
19 };

 

posted on 2015-03-24 14:52  keepshuatishuati  阅读(125)  评论(0)    收藏  举报