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.
解题思路:
本题的算法不难,不过通过率比较低,交了很多次才实现出来,因为要考虑很多方面,+-号,溢出,空格输入等,一开始没有完全考虑到这些因素。
代码:
int myAtoi(string str) {
long long int sum=0;//使用long long int型记录sum。
int f1=1,i=0,min=-2147483648,max=2147483647;
while(str[i]==' '&&str[i]!='\0')i++;//清除输入字符串前面的空格输入
if(str[i]=='-')
{
f1=-f1;//用f1标记正负性
i++;
}
else if(str[i]=='+')
{
i++;
}
for(i;i<str.size();i++)
{
if(str[i]>'9'||str[i]<'0')//判断合法性
return sum;
if(f1==1)
{
sum*=10;
sum+=str[i]-'0';
if(sum>=2147483647)//判断是否溢出
return max;
else
continue;
}
else
{
sum*=10;
sum-=str[i]-'0';
if(sum<=-2147483648)
return min;
else
continue;
}
}
return (int)sum;
}