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

my_atoi

时间:2015-02-04 21:44:50      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:

//1、找到数字字符或者加减号
//2、计算值时需要保证不溢出,将要溢出时返回最大或最小值
int
myatoi(const char *str) { if ( NULL == str ) { printf("error, param is NULL\n"); return 0; } int nIndex = 0; while ( ‘\0‘ != *(str + nIndex) ) { if ( (*(str + nIndex) >= ‘0‘ && *(str + nIndex) <= ‘9‘) || *(str + nIndex) == ‘-‘ || *(str + nIndex) == ‘+‘ ) { break; } ++nIndex; } if ( ‘\0‘ == *(str + nIndex) ) { printf("warn, there is no dest \n"); return 0; } // is negative number ? bool nFlag = false; if ( *(str + nIndex) == ‘-‘ ) { nFlag = true; ++nIndex; } else if ( *(str + nIndex) == ‘+‘ ) { ++nIndex; } int nRet = 0; while ( ‘\0‘ != *(str + nIndex) && *(str + nIndex) >= ‘0‘ && *(str + nIndex) <= ‘9‘ ) { if ( nRet > INT_MAX / 10 ) { return INT_MAX; } else if ( nRet < INT_MIN / 10 ) { return INT_MIN; } else { if ( nRet == INT_MAX / 10 && *(str + nIndex) >= ‘8‘ ) { return INT_MAX; } else if ( nRet == INT_MIN / 10 && *(str + nIndex) == ‘9‘ ) { return INT_MIN; } } int temp = *(str + nIndex) - ‘0‘; if ( nFlag ) { temp *= -1; } nRet = nRet*10 + temp; ++nIndex; } return nRet; }

 

my_atoi

标签:

原文地址:http://www.cnblogs.com/haihuahuang/p/4273262.html

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