# 引言

题目链接: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
}
更新于 阅读次数