注意if 的顺序很重要,这样才能做到一次遍历就完事
#include <stdlib.h>
#include <math.h>
#include <string>
class Solution {
public:
int strToInt(string str) {
int i=0;
int minus=1;
long numbers=0;
int size =str.size();
int flag=0;
int PN =0;
while (i<size)
{
if (str[i]=='-')
{
minus=-1;
if (flag==1) break;
flag=0;
}
else if(str[i]=='+')
{
minus=1;
if (flag==1) break;
flag=0;
}
else if (str[i]==' ')
{
if (flag==1) break;
flag=0;
}
else if(str[i]<'0'|| str[i]>'9' )
{
//只要有字母都会break
break;
}
else
{
numbers = numbers*10 +str[i]-'0';
flag=1;
}
i++;
}
numbers*=minus;
if(numbers>INT_MAX) return INT_MAX;
if(numbers<INT_MIN) return INT_MIN;
return numbers;
}
};