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.
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
下笔直接就写,结果虎头蛇尾。反复看了题目才终于搞定。上代码,已AC。
int StrToInt(string str) { bool minus = false; int sum=0; if(str.size()==0) { return 0; } for(int i =0;i<str.size();i++) { //是空格吗? if(str[i]==‘ ‘) continue; //是-吗,那后面是数字吗? if(str[i]==‘-‘) { if(str[i+1]<=‘9‘&& str[i+1]>=‘0‘) minus = true; else break; } //是+吗,那后面是数字吗? else if(str[i]==‘+‘) { if(str[i+1]>‘9‘||str[i+1]<‘0‘) break; } //是数字吗? else if(str[i]<=‘9‘&&str[i]>=‘0‘) { sum = sum*10+static_cast<int>(str[i]-‘0‘); if(str[i+1]>‘9‘||str[i+1]<‘0‘) break; if(sum>INT_MAX/10 ) { if(minus) return INT_MIN; else return INT_MAX; } if(sum == INT_MAX/10) { if(str[i+1]>=‘7‘ && minus==false) return INT_MAX; if(str[i+1]>=‘8‘ && minus==true) return INT_MIN; } } //都不是啊,那就返回咯 else break; } return minus?(-1*sum):sum; }
看看别人写的。
真是无语了。直接给链接:http://ask.julyedu.com/question/85
小小作个弊:
int atoi(const char *str) { stringstream s; // 字符串流s int a; s << str; // 把str写入流s s >> a; // 从流s中读int return a; }