首页 > 代码库 > [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. 

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.

 

从来没有写过这么复杂的atoi =_=,自己还是图样图森破,纠结了一段时间以后发现判断overflow总是写不好,果断看了别人的写法,思路就是判断在做“乘10加当前字符”操作之前,先判断结果有没有大于INT_MAX/10, 如果刚好等,则要接着判断个位数有没有益处。我这题用了unsigned其实是多此一举的。

class Solution {private:unsigned maxmount = 2147483647;unsigned minmount = 2147483648;bool isNum(char c) {    if ( c >= 0 && c <= 9) {        return true;    }    return false;}public:    int atoi(const char *str) {    unsigned cur = 0;    bool negtive =false;    unsigned result = 0;    int ret = 0;        while (str[cur] ==  ) cur++;    if (str[cur] == \0) return 0;//all whitespaces        if (!isNum(str[cur])) {        if (str[cur] == -) negtive = true;        else if (str[cur] != +) return 0;        cur++;    }        while (str[cur] != \0 && isNum(str[cur])) {        if (INT_MAX/10 < result || ((INT_MAX/10 == result) && INT_MAX%10 < (str[cur]-0)))        {            if (negtive) return INT_MIN;            return INT_MAX;        }        result = result * 10 + str[cur]-0;        cur++;    }    if (negtive) {        if (result > minmount) {//neg of            ret = INT_MIN;        }        else            ret = - result;    }    else {        if (result > maxmount) {//pos of            ret = INT_MAX;        }        else            ret = result;    }        return ret;    }};

 

[LeetCode] String to Integer (atoi)