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.
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.
难度:easy
题目:罗马数字由七个字母表示 I, V, X, L, C, D 为 M.
符号 值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如,2写法为II, 由两个I组成。12写法为XII, X + II. 数字27写法为XXVII, XX + V + II.罗马数字经常由大向小由左向右。然而4的写法并不是IIII。而是IV. 因为1在5之前就减去1得到4. 同样的原理适用于9(IX).有个6个实例用这个种减规则:I 可以放在 V (5) 和 X (10) 之前得到 4 和 9. X 可以放在 L (50) 和 C (100) 之前得到 40 和 90. C 可以放在 D (500) 和 M (1000) 之前得到 400 和 900.给出一个罗马数字,将其转成一个整数。输入保证在1到3999之间。
思路:递归,分别取当前位置与其下一位置,主要是因为IV的表示方式为V – I,要将这种减规则的数找出来单独处理。因为VII 的表示方式自左向右或自右向左都为V + I + I.
Runtime: 41 ms, faster than 57.06% of Java online submissions for Roman to Integer.
public class Solution {
public int romanToInt(String s) {
// I/1 V/5 X/10 L/50 C/100 D/500 M/1000
Map<Character, Integer> table = new HashMap<>();
table.put(‘I’, 1);
table.put(‘V’, 5);
table.put(‘X’, 10);
table.put(‘L’, 50);
table.put(‘C’, 100);
table.put(‘D’, 500);
table.put(‘M’, 1000);
return romanToInt(s, 0, table);
}
public int romanToInt(String s, int begin, Map<Character, Integer> table) {
// I/1 V/5 X/10 L/50 C/100 D/500 M/1000
// left only can keep one, rigth can keep two for V L D
if (begin + 1 == s.length()) {
return table.get(s.charAt(begin));
}
if (begin == s.length()) {
return 0;
}
int left = table.get(s.charAt(begin));
int right = table.get(s.charAt(begin + 1));
return left >= right ? left + romanToInt(s, begin + 1, table) : right – left + romanToInt(s, begin + 2, table);
}
}
发表回复