Leetcode 8. String to Integer (atoi) 题解

Last Updated At: 2016-04-09

题目链接

我的解

注意扰动情况即可,还好 leetcode WA 会提示发生错误处的测试用例,一步一步调下来即可。

8ms

int myAtoi(std::string str)
{
    bool is_negative = false;
    int res = 0;
    unsigned int digit_cnt;
    bool start = false;
    size_t i = 0;
    while(i < str.size())
    {
        if(str[i] == ' ')
        {
            i++;
            continue;
        }
        else if(str[i] == '-')
        {
            ++i;
            is_negative = true;
            break;
        }
        else if(str[i] == '+')
        {
            ++i;
            break;
        }
        break;
    }
    for(; i < str.size(); ++i)
    {
        if (str[i] >= '0' && str[i] <= '9')
        {
            if((res > INT_MAX / 10) || (res == INT_MAX / 10 && (str[i] - '0' > INT_MAX % 10)))
                return is_negative? INT_MIN:INT_MAX;
            res = res * 10 + str[i] - '0';
            continue;
        }
        break;
    }
    return (is_negative ? -res:res);
}