There are quite a lot of details to pay attentions to. But, the most important one is : watch out overflow..... Thus, the res value should be long long int type.
Better to compare with this question : http://blog.youkuaiyun.com/github_34333284/article/details/51171908
int myAtoi(string str) {
if(str.size() == 0) return 0;
int i = 0;
long long int res = 0;
bool negative = false;
while(i < str.size() && str[i] == ' ') {
i++;
}
if(str[i] == '-' || str[i] == '+') {str[i++] == '-' ? negative = true : negative = false;}
while(i < str.size()) {
if(str[i] >= '0' && str[i] <= '9') {
res = res * 10 + (str[i] - '0');
if(res > INT_MAX) return negative ? INT_MIN : INT_MAX;
} else {break;}
i++;
}
return negative ? -1 * res : res;
}