class Solution {
public:
int myAtoi(string str) {
int len = str.size();
long long result = 0;
int index;
bool flag = false;
for(int i=0; i<len; i++){
if(isspace(str[i])){
continue;
}
else if(str[i] == '-' || str[i] == '+'){
flag = (str[i]=='-')?true:false;
index = i + 1;
break;
}
else if(isdigit(str[i])){
index = i;
break;
}
else{
return 0;
}
}
while(isdigit(str[index])){
result = result*10 + (str[index] - '0');
index++;
if(result > INT_MAX){
break;
}
}
return flag?((-1)*result<INT_MIN?INT_MIN:(-1)*result):(result>INT_MAX?INT_MAX:result);
}
};
将result申明为long long就可以避免计算时就溢出的问题