// 程序员面试宝典 面试题目2 217 将字符串转化为整型 不能使用atoi函数。接口仿照atoi ,

来源:互联网 发布:益盟自动画线 源码 编辑:程序博客网 时间:2024/05/17 01:37
//************
// 程序员面试宝典  面试题目2  217    将字符串转化为整型 不能使用atoi函数。接口仿照atoi ,
// int atoi( const char *string );
/// 思路:掠过空格等特殊字符,找到符号位,标记符号位,然后找到符号位之后的连续数字字符,处理符号位。

int alphatoint (const char *nptr)
{

int isspace2(int x);
int isdigit2(int x);

int c;             // /* current char 
int total;        // /* current total 
int sign;          // /* if '-', then negative, otherwise positive 

// /* skip whitespace 
while ( isspace((int)(unsigned char)*nptr) )
++nptr;

c = (int)(unsigned char)*nptr++;
sign = c;           ///* save sign indication 
if (c == '-' || c == '+')
c = (int)(unsigned char)*nptr++;   // /* skip sign 

total = 0;

while (isdigit(c)) 
{
total = 10 * total + (c - '0');   //  /* accumulate digit 
c = (int)(unsigned char)*nptr++;  //  /* get next char 
}

if (sign == '-')
return -total;
else
return total;  // /* return result, negated if necessary 


}/// end alphatoint
int isspace2(int x) // 兼容字长不同的机器。
{
if(x==' '||x=='\t'||x=='\n'||x=='\f'||x=='\b'||x=='\r')
return 1;
else 
return 0;
}
int isdigit2(int x)
{
if(x<='9'&&x>='0')         
return 1; 
else 
return 0;

}
原创粉丝点击