题目描述:
因为一开始觉得暴力解考虑多点应该能过,然后暴力跪了几次,但是倔起来了,就是想要暴力它,最后也搞出来了,注释在代码里
代码:
class Solution {
public:
int myAtoi(string str) {
vector<char> lookup {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
vector<int> number;
string judgeNegtive = "-";
string judgePos = "+";
string whitespace = " ";
//正数符号是否出现
int pos = 0;
//是否是负数
int negitve = 0;
//符号有效
int negitveEnable = 0;
//是否是第一个字符
int first = 0;
int firstZero = 0;
int firstNonWhitespace = 0;
int firstPosNegtive = 0;
//验证上面的参数是否失效
int firstNonWhitespaceEnable = 0;
for(int i = 0; i < str.length(); i++){
if(firstNonWhitespace == 0 && whitespace[0]!=str[i]&&judgeNegtive[0]!=str[i]&&judgePos[0]!=str[i]){
//第一个非空白字符
firstNonWhitespace = 1;
}
if(firstPosNegtive == 1&&first == 0 &&(judgeNegtive[0]==str[i]||judgePos[0]==str[i])) return 0;
if((judgeNegtive[0]==str[i]||judgePos[0]==str[i])&&firstPosNegtive==0){
firstPosNegtive = 1;
}
//符号和数字隔很远的情况
if(str[i] == judgeNegtive[0]){
negitve = 1;
}
//符号和数字隔很远的情况
if(str[i] == judgePos[0]){
pos = 1;
}
int isD = 0;
//判断是否是数字
for(int j = 0; j < lookup.size(); j++){
if(str[i] == lookup[j]){
//是数字字符
if(first == 0){
if(str[i] == lookup[0]){
isD = 1;
//看看前一个是否是负数
if(i > 0&&firstZero==0){
if(str[i - 1] == judgeNegtive[0]){
negitve = 1;
negitveEnable = 1;
}else{
if(negitve == 1) return 0;
}
if(str[i - 1] != judgePos[0] && pos == 1) return 0;
}
firstZero = 1;
break;
}
//看看前一个是否是负数
if(i > 0&&firstZero==0){
if(str[i - 1] == judgeNegtive[0]){
negitve = 1;
negitveEnable = 1;
}else{
if(negitve == 1) return 0;
}
if(str[i - 1] != judgePos[0] && pos == 1) return 0;
}
first = 1;
}
//顺着存,然后倒着取
number.push_back(j);
isD = 1;
break;
}
}
if(isD == 0 && firstNonWhitespace == 1 && firstNonWhitespaceEnable == 0){
return 0;
}
//不等于空白才失效,因为第一个是非空白
if(str[i] != whitespace[0]) firstNonWhitespaceEnable = 1;
//判断是否断开了
if((first == 1||firstZero==1) && isD == 0){
break;
}
}
//判断是否超越边界
if(number.size() > 10){
if(negitve == 1 && negitveEnable == 1){
return INT_MIN;
}else{
return INT_MAX;
}
}else{
//数量级至少是在10位级的
long result = 0;
int n = 0;
for(int i = number.size()-1; i >= 0; i--){
result += pow(10, n) * number[i];
n++;
}
//上下界判断
if(negitve == 1 && negitveEnable == 1){
if(-result < INT_MIN) return INT_MIN;
else return -result;
}else{
if(result > INT_MAX) return INT_MAX;
else return result;
}
}
}
};