本文主要是介绍Write a program to convert string to number without using library function。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、问题
/*
Write a program to convert string to number without using library function。
*/
2、算法
#define MAX_LONG 0X7FFFFFFFlong foo(const char* str)
{
int sign = 1 ;
long num = 0 ;
const char* p = str ;
//假设输入的字符串是合法的
if ( *p == '-' )
{
sign = -1 ;
p++ ;
}else if ( *p == '+' )
{
sign = 1 ;
p++ ;
}
while(*p)
{
// long 取值范围-2147483648~ 2147483647
if ( (num > LONG_MAX/10) ||( (num == LONG_MAX/10) &&
( (-1 == sign && *p > '8') || (1 == sign && *p > '7')) ))
{
printf("out of bound") ;
return 0 ;
}
if ( *p >='0' && *p <='9' )
{
num = num*10 + (*p - '0') ;
}
*p++ ;
}
printf("%d", num * sign) ;
return num * sign ;
}
这篇关于Write a program to convert string to number without using library function。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!