题目大意:实现atoi函数,这个函数是实现字符串转成整数的功能
题目分析:本题的关键在于特殊情况的处理。
特殊情况实在太多,但只要通过一次次提交,知道自己的代码在哪些样例上通不过,然后修改代码使其覆盖这个样例即可。
特殊样例:
"" 、" +004500" 、"+-2" 、" 003" 、"1a"等等
代码展示:
class Solution {
public:
int myAtoi(string str) {
long long result = 0;
bool flag = true;
int pos = -1;
bool temp = false; //表示是否出现了第一个有效的符号
for(int i=0;i<str.length();i++){
if((str[i]==' '|| str[i]=='0')&&(pos==-1)){ //表示前面的字符无效
continue;
}
else{
pos = i;
}
if(str[i]=='+' && !temp){
temp = true;
continue;
}
if(str[i]=='-' && !temp){
flag = false;
temp =true;
continue;
}
if(str[i]<'0'||str[i]>'9'){ //出现有 非整数的情况,则跳出循环
break;
}
result = result*10 + (str[i]-'0');
if(result >= 2147483648){
result = 2147483648;
break;
}
}
if(!flag){
result = 0 - result;
}
if(result >= INT_MAX){
result = INT_MAX;
}
if(str[0]!=' ' && (str[0]<'0' || str[0]>'9') && str[0]!='+' && str[0]!='-') //表示非有效数字
result = 0;
return result;
}
};