避免几个坑:
1.空字符串
2.正数负数
3.不合法的字符
4.头部为0
5.超过最大值最小值
6.头部有空格
class Solution {
public:
int myAtoi(string str) {
if(str.size()<=0) return 0;
char bottom = '0';
char top = '9';
int size = str.size();
long long int temp= 0;
int cursor = 0;
bool flag = true;
while(cursor < size && str[cursor]==' ') cursor++;//去除空格
if(str[cursor] == '-'){
flag = false;
cursor++;
}else if(str[cursor] == '+'){
cursor++;
}
while(cursor < size && str[cursor]<=top && str[cursor] >=bottom){
temp = temp * 10 + str[cursor] - bottom;
if(flag && temp > INT_MAX) return INT_MAX;
if(!flag && (temp * -1) < INT_MIN) return INT_MIN;
cursor++;
}
return flag ? temp : temp * -1;
}
};