class Solution { public: const int min = pow(2,31) * (-1); const int max = pow(2,31) - 1; int StrToInt(string s) { int sign = 0; //符号 int len = s.length(); //字符串长度 int signcount = 0; //符号个数 vector<int> rec; for(int i =0;i < len;i++){ if(s[i] == '+' || s[i] == '-'){ signcount ++; if(s[i] == '-') sign = 1; //符号置1 if(signcount > 1) return 0; //符号个数大于1个,出错返回0 } else if(s[i] == '0' || s[i] == '1' || s[i] == '2' || s[i] == '3' || s[i] == '4' || s[i] == '5' || s[i] == '6' || s[i] == '7' || s[i] == '8' || s[i] == '9'){ rec.push_back(s[i] - '0'); //前面只有空格和符号,碰到数字插入数字即可 if(i+1 <len && s[i+1] != '0' && s[i+1] != '1' && s[i+1] != '2' && s[i+1] != '3' && s[i+1] != '4' && s[i+1] != '5' && s[i+1] != '6' && s[i+1] != '7' && s[i+1] != '8' && s[i+1] != '9') break; //数字的下一位不是数字,说明当前合法数字已提取完毕,可以退出 } else if(s[i] == ' ') continue; //如果碰到数字前是空格,就继续 else break; //碰到数字前,遇到非符号,非空格 结束 } if(rec.size() == 0) return 0; long sum = 0; for(auto x : rec){ sum = sum * 10 + x; if(sum > max){ //超过最大值最小值,返回最大值或最小值 if(sign == 1) return min; else return max; } } if(sign == 1) return sum * (-1); else return sum; } };