8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

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.

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.

思路:题目不难,但是很多情况要考虑清楚,"",  "+",  "     +0 123",  "123ab2",以及越界的情况

 1 class Solution {
 2 public:
 3     string getInteger(string &str)
 4     {
 5         int idx=0;
 6         for(idx=0; idx<str.size(); ++idx)
 7         {
 8             if(str[idx]<'0' || str[idx]>'9')break;
 9         }
10         return str.substr(0, idx);
11     }
12     int myAtoi(string str) {
13         if(str.size()==0)return 0;
14         int idx=0;
15         while(idx<str.size() && str[idx]==' ')++idx;//开头先去空格
16         str=str.substr(idx, str.size()-idx);
17         bool isActive=true;
18         if(str[0]>'9' || str[0]<'0')
19         {
20             if(str[0]!='+' && str[0]!='-')return 0;
21             if(str[0]=='-')isActive=false;
22             str=str.substr(1, str.size()-1);//去正负号
23         }
24         string validStr=getInteger(str);//得到有效数字
25         if(validStr.size()==0)return 0;
26         if(validStr.size()>10)//int型,长度大于10肯定越界
27         {
28             if(isActive)return INT_MAX;
29             else return INT_MIN;
30         }
31         long n=0;
32         for(int idx=0; idx<validStr.size(); ++idx)
33         {
34             n=n*10+validStr[idx]-'0';
35         }
36         if(!isActive)n=-n;
37         if(n>INT_MAX)return INT_MAX;
38         if(n<INT_MIN)return INT_MIN;
39         return n;
40     }
41 };

 

posted @ 2017-12-31 17:54  jeysin  阅读(110)  评论(0编辑  收藏  举报