approach 1
push digits & check before overflow
follow the algorithm step by step, pay attention to the difference between positive case and negative case when checking overflow and pushing digit.
C++ code
class Solution {
public:
int myAtoi(string s) {
int res = 0, n = s.size(), i = 0;
bool is_minus = false;
while (i < n && s[i] == ' ') i++;
if (i < n) {
if (s[i] == '-') is_minus = true, i++;
else if (s[i] == '+') i++;
}
while (i < n && s[i] >= '0' && s[i] <= '9') {
int t = s[i] - '0';
if (!is_minus) {
if (res > (INT_MAX - t) / 10) return INT_MAX;
res = res * 10 + t;
}else {
if (res < (INT_MIN + t) / 10) return INT_MIN;
res = res * 10 - t;
}
i++;
}
return res;
}
};