Roman numerals are represented by seven different symbols: I, V, X, L, C, Dand 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:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(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.
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.
分析
这一道题与 Integer to Roman为相反的题目,这道题会简单一点。罗马数转数字的关键在于如果处理4,9这样的数字,我们采用的处理方式时,从前向后遍历,但是每次都判断一下该位代表的数字与前一个数字的关系是不是5倍或者10倍,如果是的话,证明该位数字是4或9,只需要将之前已经累加的给删除掉,加上这两个字符实际代表的数字即可。如果不是5或10倍,直接累加。
Code
class Solution {
public:
int romanToInt(string s) {
map<char, int> nums;
nums.insert(make_pair('I', 1));
nums.insert(make_pair('V', 5));
nums.insert(make_pair('X', 10));
nums.insert(make_pair('L', 50));
nums.insert(make_pair('C', 100));
nums.insert(make_pair('D', 500));
nums.insert(make_pair('M', 1000));
int length = s.size();
int lastNum = 0;
int res =0;
for (int i = 0; i < length; i++)
{
int num = nums[s[i]];
if (lastNum != 0 && (num/lastNum == 5 || num/lastNum == 10))
{
num = num-lastNum;
res = res - lastNum;
}
lastNum = num;
res += num;
}
return res;
}
};
运行效率
Runtime: 28 ms, faster than 90.54% of C++ online submissions for Roman to Integer.
Memory Usage: 10.6 MB, less than 97.97% of C++ online submissions forRoman to Integer.

412

被折叠的 条评论
为什么被折叠?



