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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
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.
这个题目我们要考虑到多种情况如上面的Requirements for atoi
1.如果必要的话我们的函数在开始处可以抛弃很多空白的字母,指导我们发现第一个不是空白的字母。然后,从这个字母开始,采用可能存在的+号
或者-号后面跟着许多数字然后把他们翻译为数值
2.这个字符串可以在形成整型的数字后面包括例外的字母,我们把这些字母忽略,同时这些字母对函数没有影响
3.如果第一个非空字母不是个有效的数字,或者句子是空的或者只包含空白字母,没有转换发生
4.如果没有有效的转换发生,我们返回0,如果正确的数值越界了,我们则返回INT_MAX或者INT_MIN
看完要求想必实现atoi就容易多了,最主要的是找到第一个有意义的字母,何时终结,以及越界时我们返回相应的INT_MAX或者INT_MIN
unsigned long long result = 0; bool validtag = false; bool plus_minus = true; for (int i = 0;i < str.size();++i) { if (!validtag) { if (str[i] == ' ') { continue; } else if (!validtag && (str[i] == '+' || str[i] == '-' || '0' <= str[i] && str[i] <= '9')) { if (str[i] == '+') { if ((i + 1 < str.size()) && '0' <= str[i + 1] && str[i] <= '9') { validtag = true; plus_minus = true; ++i; } else return 0; } if (str[i] == '-') { if ((i + 1 < str.size()) && '0' <= str[i + 1] && str[i] <= '9') { validtag = true; plus_minus = false; ++i; } else return 0; } if ('0' <= str[i] && str[i] <= '9') { validtag = true; result += str[i] - 48; ++i; } } else { return 0; } } if (validtag && (i < str.size()) && ('0' <= str[i] && str[i] <= '9')) { result = result * 10 + str[i] - 48; if (plus_minus&& result >= 2147483647) { return INT_MAX; } if (!plus_minus&&result >= 2147483648) { return INT_MIN; } } else { if (plus_minus) return result; else return 0 - int(result); } } if (plus_minus) return result; else return 0 - int(result); } };