题目:
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.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
class Solution {
public:
int atoi(const char *str) {
int ans = 0;
int sign = 1;
//跳过前面空格
while (isspace(*str))
str++;
if (*str == '-')
sign = -1;
if (*str == '+' || *str == '-')
str++;
while (isdigit(*str)) {
int d = *str - '0';
if (INT_MAX / 10 >= ans)
ans *= 10;
else
return sign == 1 ? INT_MAX : INT_MIN;
if (INT_MAX - d >= ans)
ans += d;
else
return sign == 1 ? INT_MAX : INT_MIN;
str++;
}
return sign == 1 ? ans : -ans;
}
};
本文介绍了一个将字符串转换为整数(atoi)的C++实现方法。该方法首先忽略字符串开头的所有空白字符,然后根据正负号确定整数符号,并逐个读取后续数字字符进行转换。
234

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



