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.
class Solution {
public:
int atoi(const char *str) {
const int n = strlen(str);
int res = 0;
int sign = 1;
int i = 0;
while (i < n && str[i] == ' ') {
i++;
}
if (str[i] == '-') {
sign = -1;
i++;
} else if (str[i] == '+') {
i++;
}
for ( ; i < n; i++) {
if (str[i] > '9' || str[i] < '0') {
break;
}
if (res > INT_MAX/10 || (res == INT_MAX/10 && (str[i]-'0')>INT_MAX%10)) {
return sign>0?INT_MAX:INT_MIN;
}
res = res*10 + (str[i] - '0');
}
return sign*res;
}
};
本文详细解析了atoi函数的实现原理,包括符号处理、数字读取、边界检查和返回值处理,旨在帮助开发者深入理解字符串转整数的过程。
231

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



