程序员100道面试题17把字符串转换成整数

来源:互联网 发布:上众划算淘宝会不会查 编辑:程序博客网 时间:2024/05/17 04:37
int StrToInt(const char* str){g_nStatus = kInvalid;long long num = 0;// attentionif(str != NULL){const char* digit = str;// the first char in the string maybe '+' or '-'bool minus = false;if(*digit == '+')digit ++;else if(*digit == '-'){digit ++;minus = true;}// the remaining chars in the stringwhile(*digit != '\0'){if(*digit >= '0' && *digit <= '9'){num = num * 10 + (*digit - '0');// overflow  cout<<endl<<"in overflow "<<num<<endl;if(num>std::numeric_limits<int>::max()){num = 0;//cout<<endl<<"in overflow "<<num<<endl;break;}digit++;}// if the char is not a digit, invalid inputelse{num = 0;break;}}if(*digit == '\0'){g_nStatus = kValid;if(minus)num = 0 - num;}}return static_cast<int>(num);}

原创粉丝点击