这道题目本身并不难,难点是"consider all possible input cases"
1)首先需要过滤数字开始前的空格
2)必须以正号或负号或数字开始,形成一个合法的数字,遇到其他字符后数字结束
3)int类型的数字比如在范围-(INT_MAX+1)~INT_MAX,超过这个值的数字,整数返回INT_MAX,负数返回-(INT_MAX+1)
class Solution {
public:
int myAtoi(string str) {
int len = str.size();
int sign = 1,i = 0,flag = 0,sflag = 0;
long n = 0;
for(i = 0; i < len; ++i){
if(str[i] != ' ')
break;
}
for(; i < len; ++ i){
if(str[i] == '-' && sflag == 0){
sflag = 1;
sign = (-1);
}else if(str[i] == '+' && sflag == 0){
sflag = 1;
sign = 1;
}else if(str[i] >= '0' && str[i] <= '9'){
n = n * 10 + (str[i] - '0');
if(n > INT_MAX && sign == 1){
n = INT_MAX;
break;
}else if (n-1 > INT_MAX && sign == -1){
n = INT_MAX + 1;
break;
}
}else{
break;
}
}
n = n * sign;
return n;
}
};