atoi()函数是在笔试面试中经常考到的一个题目,主要考察是,int的溢出,字符过滤等问题下面是具体实现:
#define INT_MAX = 32767
#define INT_MIN=-32768
int atoi(const char * str){
if(!str) return 0;
int result = 0;
int sign = 1;
//提取+ -号
if(*str == '-' || *str == '+')
{
if(*str = ='-')
{
sign = -1;
}
str++;
}
while('0'<*str && *str<'9')
{
int digit = *str - '0';
if(result > INT_MAX || (sign > 0?(reslut == INT_MAX/10 &&digit > INT_MAX%10):(result == (unsigned int)(INT_MAX+1)/10 && digit > (unsigned int)(INT_MAX+1) % 10)))
{
return sign>0? INT_MAX : INT_MIN;
}
result = result*10+digit;
str++;
}
return result*sign;
}
注意整数范围,如果是有符号的整数,最大的时候加1就变成最小负数了,最小负数加1就变成最大负数了。、。。。