Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.
Symbol | Value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
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:
Given a Roman numeral, convert it to an integer.
罗马数字由七个不同的符号表示:I、V、X、L、C、D和M。
符号 | 值 |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
例如,数字2用罗马数字表示为II,即两个1相加。数字12用XII表示,即X + II。数字27用XXVII表示,即XX + V + II。
罗马数字通常从左到右按从大到小的顺序书写。然而,数字4的表示并不是IIII,而是IV。这是因为1放在5的前面,所以我们要减去它,得到4。同样的原则适用于数字9,它表示为IX。总共有六种情况需要使用减法:
给定一个罗马数字,将其转换成整数。
Example 1:
Input: s = “III”
Output: 3
Explanation: III = 3.
Example 2:
Input: s = “LVIII”
Output: 58
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: s = “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, and IV = 4.
Constraints:
首先,我们需要了解罗马数字的表示方法和规则,以便将其转换成整数。
解题算法如下:
sum
,并将其值初始化为字符串 s
中最后一个字符对应的值。s
的倒数第二个字符开始向前遍历字符串:
sum
即为转换后的整数值。这个算法利用了罗马数字的特性,从右向左遍历字符串,根据当前字符和下一个字符的大小关系来决定是加还是减,最终累加得到整数值。
class Solution {
public:
int romanToInt(string s) {
std::unordered_map<char, int> roman = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}};
int sum = roman[s.back()]; // 初始化为字符串最后一个字符的值
// 从倒数第二个字符开始向前遍历
for (int i = s.length() - 2; i >= 0; i--) {
// 如果当前字符代表的数字小于它右边的数字,减去当前数字
if (roman[s[i]] < roman[s[i + 1]]) {
sum -= roman[s[i]];
} else {
// 否则,加上当前数字
sum += roman[s[i]];
}
}
return sum;
}
};