class Solution {
public:
int myAtoi(string str) {
int base=0;
int sign=1;
int i=0;
while(str[i]=' ')
i++;
//judge sign
if(str[i]=='+') {
sign=1;
i++;
}
if(str[i]=='-') {
sign=-1;
i++;
}
while(str[i]>='0'&&str[i]<='9'){
//judge overflow
if((base>214748364)||(base==214748364&&((str[i]-'0')>7){
if(sign==1)
return 2147483647;
else
return -2147483648;
}
base=base*10+(str[i++]-'0');
}
return base*sign;
};
首先解决空格
接着解决符号
然后判断数字,解决非法输入
判断溢出
网友评论