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.

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.

思路:這道題就是把數字字符串轉化爲數字。首先要跳過前面的空格,而後可能會遇到"+"、"-"記錄其標誌信息,而後循環遍歷數字字符,直到遇到沒數字字符或"\0"結束。而後將所得結果與flag標誌相乘;左後與INT_MAX和INT_MIN比較。返回結果。git

class Solution {
public:
    int atoi(const char *str) {
        if(str==NULL)
            return 0;
        int flag=1;
        long long result=0;
        while(*str==' ')
            str++;
        if(*str=='-')
            flag=-1;
        if(*str=='+'||*str=='-')
            str++;
        while(*str>='0'&&*str<='9')
        {
            result=result*10+(*str-'0');
            str++;
        }
        result=flag*result;
        if(result>INT_MAX)
            return INT_MAX;
        else if(result<INT_MIN)
            return INT_MIN;
        return result;
    }
};
相關文章
相關標籤/搜索