程序员面试题精选100题(04)-把字符串转换成整数 (2)

时间:2019-09-22 编辑:多美文
digit ++;
            else if(*digit == '-')
            {
                  digit ++;
                  minus = true;
            }

            // the remaining chars in the string
            while(*digit != '\0')//循环截止条件
            {
                  if(*digit >= '0' && *digit <= '9')//判断字符串是否为数字
                  {
                        num = num * 10 + (*digit - '0');//核心转换公式

                        // overflow  
                        
if(num > std::numeric_limits<int>::max())//判断是否溢出
                        {
                              num = 0;

                              break;
                        }


                        digit ++;
                  
}

                  // if the char is not a digit, invalid input
                  else //是否含有非数字字符
                  {
                        num = 0;
                        break;
                  }
            }

            if(*digit == '\0')//判断字符串是否转换完毕
            {
                  g_nStatus = kValid;
                  if(minus)
                        num = 0 - num;
            }
      }

      return static_cast<int>(num);
}
本文已影响
相关文章