以前上机的时候写过的题目,不过当时没有考虑越界这些情况
class Solution {
public:
int myAtoi(string str) {
unsigned long len = str.size();
//下标
int index = 0;
while(str[index] == ' '){
index++;
}
if(index == len){
return 0;
}
// + -
int sign = 1;
if(str[index] == '+'){
index++;
}else if(str[index] == '-'){
sign = -1;
index++;
}
int res = 0;
while(index < len){
char cur = str[index];
if(cur > '9' || cur < '0'){
break;
}
if(res > INT_MAX / 10 || (res == INT_MAX / 10 && (cur - '0') > (INT_MAX % 10))){
return INT_MAX;
}
if(res < INT_MIN / 10 || (res == INT_MIN / 10 && (cur - '0') > -(INT_MIN % 10))){
return INT_MIN;
}
res = res * 10 + sign * (cur - '0');
index++;
}
return res;
}
};