leetcode String to Integer (atoi)

leetcode  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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 

 
这道题的测试用例特别多。
首先,题意就是字符串转换成int型,看起来挺简单的,最好还是把hint看一下,看哪些情况需要考虑。、
hint里说到一下几点:
1.刚开始的空格可以被忽略。
2.空格忽略以后+或-表示一个数的正负,当然没有默认为正。
3.当开始转换数字后,遇到不是有效的数字就不转换了。(什么都没有转换的情况下,返回0)
4.当转换的结果大于32位int型所能表示的最大数或者最小数,用INT_MAX (2147483647) 以及 INT_MIN (-2147483648) 代替。
 
然后我们就要看怎么做了。
1.我用了一个bool值来判断是否为正/负,当然感觉这招有点不太行。
2.while循环去掉空格。
3.根据+/-号判断正负
4.读取数字ret=ret*10+str[i]-'0'
5.判断是否溢出(用long long int来存结果,然后跟2147483647比大小
 
 1 class Solution {
 2 public:
 3     int myAtoi(string str) {
 4         const int maxint=0x7fffffff;  
 5         const int minint=0x80000000;  
 6         long long ret=0;
 7         bool negative=false;
 8         if(str=="") return ret;
 9         int i=0;
10         while(str[i]==' ') i++;
11         if(str[i]=='-'||str[i]=='+') {
12               if(str[i]=='-') negative=true;
13               i++;}
14         while(i<str.length()){
15               if('0'<=str[i]&&str[i]<='9') {
16                   ret=ret*10+str[i]-'0';
17                   i++;
18                   if(ret>maxint){
19                       if(negative){
20                           if(ret>maxint+1) return minint;
21                       }
22                       else return maxint;
23                   }}
24               
25               else break;
26             }
27         if(negative) return ret*=-1;
28         else return ret;}
29         
30 };