【题目描述】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.
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.
字符串转化成整形,要求从第一个不是空格的字符开始算,最长的连续的一串可以转化成int类型的子串,这个子串如果能转化成int类型可以表示的数字就返回该数字,如过不可以就返回0。比如:“ 2132141dasfas123123”返回2132141,“dasas12412412”返回0,当然如果子串是以“-”“+”开头的话就要看后面的字符情况。
【解题思路】做完这个题目后看了discuss中得分很高的一个C++写法,这个写法非常简单,用了C++标准库的Stringstream中流之间的输入输出来控制类型的转化,所以精髓还在于对流的输入输出理解。
【考查内容】字符串
class Solution {
public:
int atoi(const char *str) {
int out = 0;
stringstream ss;
ss << str;
ss >> out;
return out;
}
};