LeetCode题目:String to Integer (atoi)

要注意临界状态



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



代码,32ms过大集合

class Solution {
public:
    int atoi(const char *str) {
        int i = 0;
        int sign = 1;
        bool innum = false;
        int max =  2147483647;
        int premax = 214748364;
        int min = -2147483648;
        while(*str != '\0') {
            char c = *str;
            if(c >= '0' && c <= '9') {
                innum = true;
                int digit = c - '0';
                bool overflow = false;
                if(i - premax >= 1) {
                    overflow = true;
                } else if (i == premax) {
                    overflow = digit > 7;
                }
                if(overflow) 
                    return (sign == 1 ? max : min);
                i = 10 * i + (c - '0');
            } else {
                if(innum) break;
                if (c == '-') {
                    sign = -1;
                    innum = true;
                } else if(c == '+') {
                    innum = true;
                } else if(c!= ' ') {
                    break;
                }
            }
            ++str;
        }
        return sign * i;
    }
};

“LeetCode题目:String to Integer (atoi)”的一个回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注