StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/integer-to-roman/description/

# 题目大意

输入一个整型数字, 将这个数字转换为罗马数字

有如下约定

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
  • Example
Input: 3
Output: "III"

Input: 4
Output: "IV"

Input: 9
Output: "IX"

Input: 58
Output: "LVIII"
Explanation: C = 100, L = 50, XXX = 30 and III = 3.

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

# 题解

# 一句话题解

一个简单模拟, 按照罗马数字的构造方式模拟即可(**Hint:**关于9或者4的特殊情况可以通过手动构造符号映射避免额外的判断)

# 复杂度

时间复杂度 O(n)

空间复杂度 O(n)

# AC代码

c++版本

class Solution
{
  public:
    string intToRoman(int num)
    {
        vector<pair<int, string>> romanSymbol{
            {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
            {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},
            {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};
        vector<pair<int, string>>::const_iterator iter = romanSymbol.cbegin();
        string ans = "";
        while (num > 0 && iter != romanSymbol.cend())
        {
            if (num >= iter->first)
            {
                num -= iter->first;
                ans += iter->second;
            }
            else
            {
                ++iter;
            }
        }
        return ans;
    }
};

go版本

type roman struct {
	value  int
	symbol string
}

func intToRoman(num int) string {
	romans := []roman{
		{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
		{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},
		{10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}
	ans := ""
	index := 0
	for num > 0 {
		if num >= romans[index].value {
			num -= romans[index].value
			ans += romans[index].symbol
		} else {
			index++
		}
	}
	return ans
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

1 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读使用 + / − 按钮缩放 · 放大视图后可拖动 · 点击节点阅读单指拖动平移 · 使用 + / − 按钮缩放 · 点击节点阅读

当前文章引用本文
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用0

暂无

文章关联