今天的题目是 leetcode 的 字符串转换整数
写的比较垃圾
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| class Solution { constexpr static char kSpace = ' '; constexpr static char kMinus = '-'; constexpr static char kPlus = '+';
bool prefix_checked = false; bool is_minus = false; bool number_checked = false;
public: int myAtoi(string s) { using limit_t = ::std::numeric_limits<::std::int32_t>; ::std::int64_t res = 0; for (auto i = 0; i < s.size(); i++) { if (s[i] == kSpace) { if (number_checked) { break; } else if (prefix_checked) { return 0; } else { continue; } }
if (s[i] == kPlus) { if (number_checked) { break; } else if (prefix_checked) { return 0; } else { prefix_checked = true; continue; } }
if (s[i] == kMinus) { if (number_checked) { break; } else if (prefix_checked) { return 0; } else { is_minus = true; prefix_checked = true; continue; } }
if (s[i] < '0' || s[i] > '9') { break; }
res = res * 10 + s[i] - '0'; number_checked = true; if (res > limit_t::max()) { return is_minus ? limit_t::min() : limit_t::max(); } if (res < limit_t::min()) { return limit_t::min(); } } if (is_minus) res = -res; return res; } };
|
前面几个判断主要是跳过字符串前的空字符, 确定前缀符号, 在badcase时直接返回0, 超过上限时返回上限
这是一个状态机实现, 管理了三个状态, 实现不太漂亮