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.
思路挺清晰的 但是代码不太简洁
以下是top vote
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;
}
本文介绍了一个将字符串转换为整数的atoi函数实现方法,并详细讨论了处理各种输入情况的细节,包括空格、符号和数字字符等。文章还强调了在实现过程中需要考虑的所有边界条件。

482

被折叠的 条评论
为什么被折叠?



