1,题目要求
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, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven 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:
- 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.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: “III”
Output: 3
Example 2:
Input: “IV”
Output: 4
Example 3:
Input: “IX”
Output: 9
Example 4:
Input: “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
罗马数字由七个不同的符号表示:I,V,X,L,C,D和M.
符号 | 价值 |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
例如,两个用罗马数字写成II,只有两个加在一起。十二写为XII,简称为X + II。第二十七号写成XXVII,即XX + V + II。
罗马数字通常从左到右从最大到最小。但是,四个数字不是IIII。相反,第四个写为IV。因为一个在五个之前,我们减去四个。同样的原则适用于九号,即九号。有六个使用减法的实例:
- I可以放在V(5)和X(10)之前制作4和9。
- X可以放在L(50)和C(100)之前,使其成为40和90。
- C可以放在D(500)和M(1000)之前,以产生400和900。
给定罗马数字,将其转换为整数。输入保证在1到3999的范围内
给定罗马数字,将其转换为整数。输入保证在1到3999的范围内。
2,题目思路
对于这道题,要求就出给定的罗马数字字符串所表示的值。
对于罗马字符而言,字符与值的表示正如上面的表所示,而对于一个罗马数字,如果两个连续的罗马字符,左侧的比右侧的小,说明是右侧的值减去左侧的值:
- IV:1小于5,因此这个数字表示的值就是5-1=4
反之,就是进行相加:
- VI:5大于1,因此这个数字表示的值为5+1=6
因此,这道题就是从右往左,相邻元素进行比较即可。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> romanMap {{'I', 1},{'V', 5},
{'X',10},{'L', 50},
{'C',100},{'D',500},
{'M',1000}};
int n = s.size();
int res = romanMap[s[n-1]];
for(int i = n-2;i >= 0;i--){
if(romanMap[s[i]] < romanMap[s[i+1]])
res -= romanMap[s[i]];
else
res += romanMap[s[i]];
}
return res;
}
};