避坑——别开long long,用long double,不然有个数据过不了!
暴力枚举,,有个数据一直过不了,最后看了讨论区发现是这个问题
还有就是如果开头前缀是字母那肯定是不合法的,直接输出0即可
class Solution {
public:
int strToInt(string str) {
int start_idx;
long double res;
int length = 0;
int flag = 0; //用来判断整数字符串中是否有整数出现
if((str[0] >= 'a' && str[0] <= 'z') || (str[0] >= 'A' && str[0] <= 'Z') )
return 0;
for(int i = 0; i < str.size(); i++) //预处理,找到第一个有效的非空格字符
{
if(str[i] != ' ' && (str[i] == '+' || str[i] == '-' || (str[i] >= '1' && str[i] <= '9')))
{
start_idx = i;
flag = 1;
break;
}
}
if(str[start_idx] == '+' || str[start_idx] == '-') //先碰到+ -
{
if(str[start_idx] == '+') //是正数,正常处理
{
start_idx++;
while(str[start_idx] == '0') start_idx++;
if(str[start_idx] >= '1' && str[start_idx] <= '9')
{
length++;
res = str[start_idx] - '0'; //字符转化成数字
}
}
else //先碰到减号,说明是负数
{
start_idx++;
while(str[start_idx] == '0') start_idx++;
if(str[start_idx] >= '1' && str[start_idx] <= '9')
{
length++;
res = -1*(str[start_idx] - '0');
}
}
}
else //先碰到数字
{
length++;
res = str[start_idx] - '0';
}
for (int i = start_idx + 1; str[i] >= '0' && str[i] <= '9'; i++)
{
if (res < 0) res = -(-res * 10 + (str[i] - '0'));
else res = res * 10 + (str[i] - '0');
}
if(!flag || !length) return 0;
if (res > pow(2, 31) - 1) return INT_MAX;
else if (res < -1 * pow(2, 31)) return INT_MIN;
else return res;
}
};