使用全局变量来记录返回值是否正确;
//符号
//非法字符
//溢出
enum Status{kValid = 0,kInValid}
int g_Status = kValid;
int strToInt(string s){
int len = s.size();
g_Status = kInValid;
long long num = 0;
int index=0;
bool minus = false;
if(len != 0){
//开始符号的问题
if(s[0] == '+') index++;
eles if(s[0] == '-'){
minus = true;
index++;
}
else{
num = strToIntCore(s,index,minus);
}
}
return (int)num;
}
long long strToIntCore(string s,int index,bool minus){
int len = s.size();
long long num = 0;
while(index < len){
if(s[index] >= '0' && s[index] <= '9'){
int flag = minus?-1:1;
num = num*10 + flag*(s[index]-'0');
//判断溢出
if((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000) ){
num = 0;
break;
}
index++;
}
else {
num = 0;
break;
}
}
if(index == len){
g_Status = kValid;
}
return num;
}