完成 算法1

This commit is contained in:
2024-12-20 10:09:07 +08:00
parent 6ea618f9ec
commit 13fea8fc31
2 changed files with 77 additions and 1 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: 算法-{{ date }}
date: {{ date }}
tags: [c++]
tags: [c++, 算法]
categories: 开发
toc: true
cover: https://cdn.jsdelivr.net/gh/Aniakea/blog_pic@main/blog/Images/IMG_0239.PNG
+76
View File
@@ -2,6 +2,7 @@
title: 算法-2024-12-19
tags:
- c++
- 算法
categories: 开发
toc: true
cover: https://cdn.jsdelivr.net/gh/Aniakea/blog_pic@main/blog/Images/IMG_0239.PNG
@@ -9,3 +10,78 @@ top_img: /img/dev.jpg
date: 2024-12-19 17:44:34
---
今天的题目是 leetcode 的 字符串转换整数
写的比较垃圾
```c++
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, 超过上限时返回上限
这是一个状态机实现, 管理了两个状态, 实现不太漂亮, 后续大概需要重写