[LeetCode]String to Integer (atoi)


タイトルの要件:
mplement 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.
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.
要求通りにコードを書くと、以下のようにまとめることができます.
1.文字列が空白またはすべて空白で、0を返します. 
2.文字列の接頭辞スペースは無視する必要があります.
3.接頭辞のスペースを無視した後、出会った最初の文字は、「+」または「-」の番号であれば、後ろに読み続けます.数値であれば、数値の処理を開始します.前の2種類でなければ、0を返します.
4.数字を処理する過程で、後の文字が数字でない場合、変換を停止し、現在の値を返す.
5.上記の処理中に、変換された値がint型の範囲を超えた場合、intの最大値または最小値が返される.
要求がはっきりしていれば、ACのコードを書くことができます.
私のコードは以下の通りです.大牛の指導交流を歓迎します.
AC,Runtime: 32 ms
//LeetCode_String to Integer (atoi)
//Written by zhou
//2013.11.13
class Solution {
public:
    int atoi(const char *str) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if (str == NULL)   //   
           return 0;
        
        //      
        int i = 0;
        while (str[i] != '\0' && str[i] == ' ')
          ++i;
          
        if (str[i] == '\0')
          return 0;
        
        int max = 0x7fffffff;
        int min = 0x80000000;
        int signal = 1;
        
        //  +、- 
        if (str[i] == '+')
        {
            signal = 1;
            ++i;
        }
        else if (str[i] == '-')
        {
            signal = -1;
            ++i;
        }
        
        //    
        long long sum = 0;
        while (str[i] != '\0')
        {
            if (str[i] >= '0' && str[i] <= '9')
                 sum = sum * 10 + signal * (str[i] - '0');
            else 
                return sum;
            if (sum > max || sum < min)   //    
                return sum > 0 ? max : min;
            ++i;
        }
        return sum;
    }
};