From 3783dc345727edf9ba4905e87ee7eb8876203433 Mon Sep 17 00:00:00 2001 From: vannessa Date: Mon, 23 Dec 2024 15:32:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BB=8A=E6=97=A5=E7=AE=97?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/_posts/1.md | 2 +- source/_posts/2.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 source/_posts/2.md diff --git a/source/_posts/1.md b/source/_posts/1.md index 876b9ae..42007de 100644 --- a/source/_posts/1.md +++ b/source/_posts/1.md @@ -84,4 +84,4 @@ public: 前面几个判断主要是跳过字符串前的空字符, 确定前缀符号, 在badcase时直接返回0, 超过上限时返回上限 -这是一个状态机实现, 管理了两个状态, 实现不太漂亮, 后续大概需要重写 +这是一个状态机实现, 管理了三个状态, 实现不太漂亮 \ No newline at end of file diff --git a/source/_posts/2.md b/source/_posts/2.md new file mode 100644 index 0000000..f05a758 --- /dev/null +++ b/source/_posts/2.md @@ -0,0 +1,61 @@ +--- +title: 算法-2024-12-23 07:17:25 +tags: + - c++ + - 算法 +categories: 开发 +toc: true +cover: https://cdn.jsdelivr.net/gh/Aniakea/blog_pic@main/blog/Images/IMG_0239.PNG +top_img: /img/dev.jpg +date: 2024-12-23 15:17:25 +--- + +今天的题目是罗马数字两件套 + +分别是 + +- 整数转罗马数字 + +- 罗马数字转整数 + +以下是题解 + +```c++ +constexpr array roman{"M", "CM", "D", "CD", "C", "XC", "L", + "XL", "X", "IX", "V", "IV", "I"}; + +constexpr array arabic{1000, 900, 500, 400, 100, 90, 50, + 40, 10, 9, 5, 4, 1}; + +class Solution { +public: + string intToRoman(int num) { + stringstream roman_str; + int arabic_idx = 0; + while (num != 0) { + if (num >= arabic[arabic_idx]) { + roman_str << roman[arabic_idx]; + num -= arabic[arabic_idx]; + } else + arabic_idx++; + } + return roman_str.str(); + } + + int romanToInt(string s) { + int rst = 0; + for (size_t i = 0; i < s.size();) { + for (size_t j = 0; j < roman.size(); ++j) { + if (s.compare(i, strlen(roman[j]), roman[j]) == 0) { + rst += arabic[j]; + i += strlen(roman[j]); + break; + } + } + } + return rst; + } +}; +``` + +主要思路是将特殊情况分别打表并进行匹配