码迷,mamicode.com
首页 > 其他好文 > 详细

Write a program to convert string to number without using library function。

时间:2014-09-03 11:19:16      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   问题   cti   sp   amp   on   c   

1、问题

/*

Write a program to convert string to number without using library function。

*/


2、算法

#define MAX_LONG 0X7FFFFFFF
long 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)
        {
                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。

标签:style   io   ar   问题   cti   sp   amp   on   c   

原文地址:http://blog.csdn.net/u011476173/article/details/39015737

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!