Cocos2d-X atoi() 函数的具体实现

来源:互联网 发布:mac air教程视频 编辑:程序博客网 时间:2024/04/28 11:41
  1. /* 8、请编写能直接实现 int atoi(const char * pstr)函数功能的代码           */  
  2. /************************************************************************/  
  3. //考虑全局变量返回结果是否有效,和大数问题  
  4. bool isToIntValid =true;  
  5. int strToInt(const char *str)  
  6. {  
  7.     long long num = 0;  
  8.     int mark = (*str== '-' ? -1: 1);  
  9.     long long upperBound = numeric_limits<int>::max();;  
  10.     if(mark == -1)  
  11.         ++upperBound;  
  12.   
  13.     const char* temp = (*str == '+' || *str == '-') ? str + 1: str;  
  14.     for( ;*temp >= '0' && *temp <= '9'; ++temp)  
  15.     {  
  16.         num = num * 10 + *temp - '0';      
  17.         if(num > upperBound)  
  18.         {  
  19.             //越界,atoi中对于越界直接取最值  
  20.             isToIntValid = false;  
  21.             num = upperBound;  
  22.             break;  
  23.         }  
  24.     }  
  25.     if(*temp !='\0' || *str == '0')  
  26.         isToIntValid = false;  
  27.     return  static_cast<int>(mark * num);   
  28. }  
  29. void testOfstrToInt()  
  30. {  
  31.     assert(atoi("+1234") == strToInt("+1234"));  
  32.     assert(atoi("-1234") == strToInt("-1234"));  
  33.     assert(atoi("+aaa234") == strToInt("+aaa234"));  
  34.     assert(atoi("aaa1234") == strToInt("aaa1234"));  
  35.     assert(atoi("-1234a") == strToInt("-1234a"));  
  36.     assert(atoi("1234") == strToInt("1234"));  
  37.     assert(atoi("12a34") == strToInt("12a34"));  
  38.     assert(atoi("aaaa") == strToInt("aaaa"));  
  39.     assert(atoi("0123") == strToInt("0123"));  
  40.     //大数  
  41.     assert(atoi("123456789012345123456") == strToInt("123456789012345123456"));  
  42.     assert(atoi("-123456789012345123456") == strToInt("-123456789012345123456"));  
  43. }
0 0