码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] String to Integer (atoi)

时间:2015-03-04 16:04:09      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

代码:

 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. 纯粹的细节题,但是感觉好多细节不明。

[LeetCode] String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/Azurewing/p/4313561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!