/*
atoi算法,要求完美版
有两种,一种是用longlong,一种是真用int
“”
" "
“-”
“+”
“ -23”
“ +23”
“12a"
"abc"
越界情况
*/
#include <iostream>
using namespace std; //方法一用 long long 取巧
int atoi(const char * str,bool & flag)
{
long long result=;
int tmp;
int sign=;
if(str==NULL)
{
flag=false;
return ;
}
while(isspace(*str))
str++;
//if(*str=='\0')
//{
// flag=false;
// return 0;
//}
if(*str=='+'||*str=='-')
{
if(*str=='-')
sign=-;
str++;
}
if(*str=='\0') //” “和”+“ ,”-“的情况
{
flag=false;
return ;
}
while(*str>=''&&*str<='')
{
tmp=*str-'';
result=result*+tmp;
if(sign==-)
{
if(result->INT_MAX) //这里注意,如果是INT_MAX+1,系统或默认转换成int,导致越界,所以用result-1,result是longlong不会越界
{
result=INT_MAX+;
flag=false;
break;
}
}
else if(result>INT_MAX)
{
result=INT_MAX;
flag=false;
break;
}
str++;
}
if(*str=='\0')
flag=true;
else
flag=false;
return sign*result;
} //方法二 用int
int atoi2(const char * str ,bool & flag)
{
int result=;
int sign=;
int tmp;
int MAX_DIV=INT_MAX/;
int MAX_R=INT_MAX%;
int MIN_R=MAX_R+; //或者为MIN_R=-(INT_MIN%10); //如果用(INT_MAX+1)%10就错了,直接加的时候越界
int MIN_DIV=(INT_MAX)/; //july用的是max=(int)((unsigned)~0>>1);
//min_r=(int)(((unsigned)~0>>1+1)%10);
if(str==NULL)
{
flag=false;
return result;
}
while(isspace(*str))
str++;
if(*str=='+'||*str=='-')
{
if(*str=='-')
sign=-;
str++;
}
if(*str=='\0')
{
flag=false;
return result;
}
while(*str>=''&&*str<='')
{
int tmp=*str-'';
if(sign==)
{
if(result>MAX_DIV||(result==MAX_DIV&&tmp>MAX_R))
{
result=INT_MAX;
flag=false;
return result;
}
}
else if(result>MIN_DIV||(result==MIN_DIV&&tmp>MIN_R))
{
result=INT_MIN; //result直接为最小-2147483648,直接返回了
flag=false;
return result;
}
result=result*+tmp;
str++;
}
if(*str=='\0')
flag=true;
else
flag=false;
return sign*result;
} int main()
{
char * str[]={""," ","abc",""," -1234"," +34"," 12bc","+","-","+++","","","+2147483648","-2147483648","-2147483649","+12123131312432342"," -122323434534534654"};
//cout<<INT_MAX<<endl;
int n=;
bool flag;
for(int i=;i<n;i++)
{
int tmp=atoi2(str[i],flag);
if(tmp==)
{
if(flag==false)
cout<<str[i]<<" 错误数据转换为: "<<tmp<<endl;
else
cout<<str[i]<<" 转换为: "<<tmp<<endl;
}
else
{
cout<<str[i]<<" 转换为: "<<tmp<<endl;
}
}
system("pause");
}