题目:
参考解法:
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;elsereturn INT_MIN;}base = 10 * base + (str[i++] - '0');}return base * sign;
}
注意这里的判断条件:
base == INT_MAX / 10 && (str[i] - '0' > 7),最后一个为什么是这个?