Question:
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.
题目大意就是把字符串转化成数,但是我看到这个题通过率很低,但是确是Eazy题,后来发现是因为要注意很多特殊情况Algorithm:
1、数字的第一个字符只能是‘+’、‘-’、数字
2、如果从第一个字符往后出现非数字的字符,即返回之前的数
3、如果第一个字符是‘-’则返回负数
4、如果int数溢出即返回INT_MAX(正)或INT_MIN(负)
Submitted Code:
class Solution { //第一个数必须是‘+’或‘-’或数字 后面如果再出现不在0~9的数,直接返回前面的数
public:
int myAtoi(string str) {
if(str.empty())return 0;
long long int res=0;
int flag=1; //flag为正负标志位
int i=0,j=0;
while(str[i] == ' ')
i++;
if(str[i] == '+')
i++;
else if(str[i] == '-')
{
i++;
flag = -1;
}
j=i;
for(j=i;j<str.size();j++)
{
if(str[j]>='0' && str[j]<='9')
{
res=res*10+(str[j]-'0');
if(res>INT_MAX)
return flag>0 ? INT_MAX : INT_MIN;
}
else if(str[j]<'0' || str[j]>'9')
return flag>0 ? res:(-1)*res;
}
return flag==1?res:(-1)*res;
}
};