首页 > 技术文章 > my_atoi

haihuahuang 2015-02-04 21:08 原文

//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; }

 

推荐阅读