先用字符串存取有效数字的字串
然后……
#include<string>
class Solution {
public:
int myAtoi(string str) {
int i = 0,f=1,n=0;
while (str[i] == ' ') ++i;
if (str[i] == '+' || str[i] == '-')
f = str[i++] == '-' ? -1 : 1;
while (str[i+n] >= '0' && str[i+n] <= '9') ++n;
string _ans = str.substr(i, n);
long long int ans = 0;
for (auto x : _ans) {
ans = ans * 10 + x - '0';
if (f*ans > INT_MAX) return INT_MAX;
if (f*ans < INT_MIN) return INT_MIN;
}
return f*ans;
}
};