1.9 KiB
1.9 KiB
title, tags, categories, toc, cover, top_img, date
| title | tags | categories | toc | cover | top_img | date | ||
|---|---|---|---|---|---|---|---|---|
| 算法-2024-12-19 |
|
开发 | true | https://cdn.jsdelivr.net/gh/Aniakea/blog_pic@main/blog/Images/IMG_0239.PNG | /img/dev.jpg | 2024-12-19 17:44:34 |
今天的题目是 leetcode 的 字符串转换整数
写的比较垃圾
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, 超过上限时返回上限
这是一个状态机实现, 管理了两个状态, 实现不太漂亮, 后续大概需要重写