LeetCode101: 8. String to Integer (atoi)
tags: Tricky,LeetCode101,Integer Overflow The key idea is how to detect integer overflow, it’s same to: LeetCode101: 7. Reverse Integer. class Solution { public: int myAtoi(string s) { auto iter = s.begin(); int base = 1, r = 0, p = 0; // Skip whitespace for (; iter != s.end() && *iter == ' '; ++iter) { } // negative or positive if (*iter == '-' || *iter == '+') { if (*iter == '-') { base = -1; } ++iter; } for (; iter != s.end(); ++iter) { // failed at here: the logic between conditions is OR not AND if (*iter > '9' || *iter < '0') { break; } p = (*iter - '0') * base; // 7 is the INX_MAX's suffix, remember? if (r > INT_MAX / 10 || (r == INT_MAX / 10 && p > 7)) { return INT_MAX; } // 8 is the INT_MIN's suffix, too. if (r < INT_MIN / 10 || (r == INT_MIN / 10 && p < -8)) { return INT_MIN; } r = r * 10 + p; } return r; } };