题目描述:
解法一:
class Solution {
public:
int myAtoi(string str) {
int index=0;
bool neg=0;
long long res=0;
while(str[index]==' ') index++;
if(str[index]!='-'&&str[index]!='+'&&(str[index]>'9'||str[index]<'0'))
return 0;
if(str[index]=='-') {neg=1;index++;}
else if(str[index]=='+') index++;
while(str[index]<='9'&&str[index]>='0'){
if((neg==0)&&(res>INT_MAX/10||(res==INT_MAX/10&&(str[index]-'0')>7))) return INT_MAX;
if((neg==1)&&(res>INT_MAX/10||(res==INT_MAX/10&&(str[index]-'0')>8))) return INT_MIN;
res=res*10+(str[index]-'0');
index++;
}
return neg? -res:res;
}
};
解法二:
class Solution {
public:
int myAtoi(string str) {
int res=0;
istringstream is(str);
is>>res;
return res;
}
};