这是Leetcode上一道难度为Easy,但是AC率倒数第二的宝搞题目。难点主要在于要兼顾各种input case。
来自leetcode discuss区域
主要要注意:
- discards all leading whitespaces (忽略符号和数字前的空格)
- sign of the number(处理正负号)
- overflow(处理overflow)
- invalid input(处理非法输入)
其他的三点处理起来都还算容易,overflow处理,我的代码是采用单独设一个long long flag 值和 return值一样,如果下一步flag>INT_MAX,就溢出了。discuss区的这个示例处理的更加好一些。
int atoi(const char *str) {
int sign = 1, base = 0, i = 0;
while (str[i] == ' ') { i++; }
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[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;
}