# 字符串转换整数 (atoi) 以下错误的选项是? ## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; cout << sol.myAtoi("-42") << endl; return 0; } ``` ## 答案 ```cpp class Solution { public: int myAtoi(string s) { int index = 0; while (index < s.length() && s[index] == ' ') index++; int sign = 1; if (index < s.length() && (s[index] == '+' || s[index] == '-')) { if (s[index] == '-') sign = -1; index++; } int val = 0; while (index < s.length() && (s[index] >= '0' && s[index] <= '9')) { if (val > (2147483647 - (s[index] - '0')) / 10) { if (sign == -1) return -2147483648; else return 2147483647; } val = val * 10 + (s[index] - '0'); index++; } return val; } }; ``` ## 选项 ### A ```cpp class Solution { public: int myAtoi(string str) { int d = 0; istringstream is(str); is >> d; return d; } }; ``` ### B ```cpp class Solution { public: int myAtoi(string str) { int i = 0; while (' ' == str[i]) ++i; long flag = 1; if ('+' == str[i]) { flag = 1; return fun(str, ++i, flag); } else if ('-' == str[i]) { flag = -1; return fun(str, ++i, flag); } else if (str[i] - '0' >= 0 && str[i] - '0' <= 9) { flag = 1; return fun(str, i, flag); } else { return 0; } } int fun(string str, int i, const long flag) { long res = 0; while (str[i] - '0' >= 0 && str[i] - '0' <= 9) { res = res * 10 + (str[i++] - '0'); if (res * flag > pow(2, 31) - 1) return INT_MAX; if (res * flag < -pow(2, 31)) return INT_MIN; } res = res * flag; return int(res); } }; ``` ### C ```cpp class Solution { public: int myAtoi(string str) { int max = INT_MAX / 10; int min = INT_MIN / 10; int max_f = INT_MAX % 10; int min_f = INT_MIN % 10; int len = str.length(); bool flag = false; int sum = 0; int symbol = 1; for (int i = 0; i < len; i++) { char ch = str[i]; if (!flag) { if (ch == ' ') continue; else if (ch == '+') flag = true; else if (ch == '-') { flag = true; symbol = -1; } else if (ch <= '9' && ch >= '0') flag = true; else break; } else if (ch > '9' || ch < '0') break; if (ch <= '9' && ch >= '0') { int pos = symbol * (ch - '0'); if (sum > max || (sum == max && pos >= max_f)) return INT_MAX; if (sum < min || (sum == min && pos <= min_f)) return INT_MIN; sum = sum * 10 + pos; } } return sum; } }; ```