[LeetCode] String to Integer (atoi)

代码:

 1 class Solution {
 2 public:
 3     int atoi(string str) {
 4         int num = 0;
 5         int sign = 1;
 6         const int n = str.size();
 7         int i = 0;
 8 
 9         while (str[i] == ' ' && i < n)
10             i++;
11 
12         if (str[i] == '+') {
13             i++;
14         }
15         else if (str[i] == '-') {
16             sign = -1;
17             i++;
18         }
19 
20         if (str[i] == '+' || str[i] == '-')
21             return 0;
22 
23 
24         for (; i < n; i++) {
25             if (str[i] < '0' || str[i] > '9')
26                 return num * sign;
27             if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10) ){
28                 return sign == -1 ? INT_MIN : INT_MAX;
29             }
30             num = num * 10 + str[i] - '0';
31         }
32         return num * sign;
33     }
34 };
 1 class Solution {
 2 public:
 3     int atoi(string str) {
 4         int num = 0;
 5         int sign = 1;
 6         const int n = str.size();
 7         int i = 0;
 8 
 9         while (str[i] == ' ' && i < n)
10             i++;
11 
12         if (str[i] == '+') {
13             i++;
14         }
15         else if (str[i] == '-') {
16             sign = -1;
17             i++;
18         }
19 
20         if (str[i] == '+' || str[i] == '-')
21             return 0;
22 
23 
24         for (; i < n; i++) {
25             if (str[i] < '0' || str[i] > '9')
26                 return num * sign;
27             if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10) ){
28                 return sign == -1 ? INT_MIN : INT_MAX;
29             }
30             num = num * 10 + str[i] - '0';
31         }
32         return num * sign;
33     }
34 };

 

杂记:

1. 纯粹的细节题,但是感觉好多细节不明。

posted @ 2015-03-04 15:50  Azurewing  阅读(118)  评论(0编辑  收藏  举报