题目描述:
8. String to Integer (atoi)
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.
解题思路:
首先忽略字符串首所有的空格,然后判断第一个是否为'+'或‘-’,使用factor记录数字的符号。如果字符串首部第一个非空字符为非法的,那么返回0,。继续处理字符串,将其转为数字。当遇到第一个非数字的字符时,即停止转换。之后还要注意,如果转换后得到的结果大于INT_MAX或者小于INT_MIN时,则返回INT_MAX或者INT_MIN。
代码展示:
//代码一
// 复杂度 O(n)
class Solution {
public:
int myAtoi(string str) {
long long ans =0 ;
int i =0;
int factor = 1;
while(str[i]==' ')
{
i++;
}
int strsize = str.size();
for( ; i<strsize;)
{
<span style="white-space:pre"> </span>
if(str[i]=='+'||str[i]=='-')
factor=(str[i++]=='-')?-1:1;
while(str[i]>='0'&&str[i]<='9'&&i<strsize)
{
ans*=10;
ans+=str[i]-'0';
i++;
if(ans*factor>INT_MAX) return INT_MAX;
else if(ans*factor<INT_MIN) return INT_MIN;
}
return ans*factor;
}
return 0;
}
};