13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
SymbolValue I1 V5 X10 L50 C100 D500 M1000
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.
符號值 I1 V5 X10 L50 C100 D500 M1000
例如,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); } }