StarryNights

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

站内检索

循着字句,邂逅星光

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

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

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

发现内容

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

快速直达

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

# 引言

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

# 题目大意

给出一个罗马数字, 将这个罗马数字转换为数字

有如下约定

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

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

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: "III"
Output: 3

Input: "IV"
Output: 4

Input: "IX"
Output: 9

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

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

# 题解

# 一句话题解

一个简单模拟, 顺序读取罗马符号将对应数值相加即可。通过观察可以发现, 当当前符号的前一个符号代表数值小于当前符号时表示9或者4这种类似的特殊情况, 此时只需要在总的数值上减去2倍前一个字符代表数值即可确保结果正确

# 复杂度

时间复杂度 O(n)

# AC代码

c++版本

class Solution
{
  public:
    int romanToInt(string s)
    {
        unordered_map<char, int> romanSymbol{{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
        int ans = 0;
        for (int i = 0; i < s.length(); ++i)
        {
            ans += romanSymbol[s[i]];
            if (i > 0 && romanSymbol[s[i]] > romanSymbol[s[i - 1]])
            {
                ans -= 2 * romanSymbol[s[i - 1]];
            }
        }
        return ans;
    }
};

go版本

func romanToInt(s string) int {
	romanSymbol := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
	ans := 0
	for i := 0; i < len(s); i++ {
		ans += romanSymbol[s[i]]
		if i > 0 && romanSymbol[s[i]] > romanSymbol[s[i-1]] {
			ans -= 2 * romanSymbol[s[i-1]]
		}
	}
	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

暂无

文章关联