LeetCode8——String to Integer (atoi)(自己编写atoi函数)

来源:互联网 发布:青年男士羽绒服知乎 编辑:程序博客网 时间:2024/05/20 13:18

题目:



参考解法:

I think we only need to handle four cases:

discards all leading whitespaces

sign of the number

overflow

invalid input

int myAtoi(char* str) {        int sign = 1, base = 0, i = 0;    while (str[i] == ' ')         { i++; }//去掉空格            if (str[i] == '-' || str[i] == '+')     {        sign = 1 - 2 * (str[i++] == '-');//这里i进行了++,注意符号也要输出的     }//判断符号        while (str[i] >= '0' && str[i] <= '9')     {        if (base >  INT_MAX / 10 || ((base == INT_MAX / 10) &&  (str[i] - '0' > 7))) //这个条件会在加到一定程度时才触发        {            if (sign == 1)                 return INT_MAX;            else                return INT_MIN;        }                base  = 10 * base + (str[i++] - '0');    }    return base * sign;}


分析:

注意这里的判断条件:

base == INT_MAX / 10 &&  (str[i] - '0' > 7),最后一个为什么是这个?