题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
#include <algorithm> #include <cmath> #include <climits> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ int StrToInt(string s) { // write code here vector<vector<int>> statesTable = { {0, 2, 2, 3, 1}, {3, 1, 2, 3, 3}, {3, 2, 2, 3, 3} }; long top = INT_MAX; long bottom = INT_MIN; int n = s.size(); int state = 0; long res = 0; int sign = 1; for (int i = 0; i < n; i++) { char c = s[i]; if (c == ' ') { state = statesTable[state][0]; if (state == 3) { break; } } else if (c == '0') { if (state == 2) { state = statesTable[state][1]; res = res * 10 + (int) (c - '0'); res = (sign > 0) ? min(res, top) : min(res, -bottom); } else { state = statesTable[state][1]; } } else if (c >= '1' && c <= '9') { state = statesTable[state][2]; res = res * 10 + (int) (c - '0'); res = (sign > 0) ? min(res, top) : min(res, -bottom); } else if (c == '+' || c == '-') { if (state == 0) { state = statesTable[state][4]; sign = (c == '+') ? 1 : -1; } else { break; } } else { state = statesTable[state][3]; break; } } return (int)sign * res; } };
一开始也以为自己写不出来,但是最终我写出来了!太棒了!
注意事项:
”0 -2“字符串转换之后为0, 因为0之后不能再接正负号。
这是我自己绘制的状态图: