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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can 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: 3Example 2:
Input: "IV" Output: 4Example 3:
Input: "IX" Output: 9Example 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.
罗马数字转换整数。
题意跟12题恰好相反。这个题依然没什么算法和思想可言,思路依然是需要创建一个整数和罗马数字之间的mapping,然后从右往左遍历input字符串。当遍历到 s[i] 的时候,需要看一下 s[i], cur 和 s[i - 1], pre 位置上的罗马数字哪个对应的整数大,分如下几种情况,用例子说明,
如果s = "III",s[i] = s[i - 1] = "I"。此时pre == cur,只要把pre位置上代表的整数加到结果即可。这种case应该是只适用于 s[i] 是"I"的,因为没有其他字母可以这样重复出现,类似"XX"或者"VV"应该都是不合法的。
如果s = "IV",s[i] = "V", s[i - 1] = "I",此时pre < cur,需要把I的值从V减去(5-1 = 4)。
如果s = "VI",s[i] = "I", s[i - 1] = "V",此时pre >= cur,这种case同第一种case,需要将I的值和V的值相加(5 + 1 = 6)。
时间O(n)
空间O(n) - hashmap记录对应关系
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var romanToInt = function (s) { 6 // corner case 7 if (s === null || s.length === 0) { 8 return 0; 9 } 10 11 // normal case 12 const map = new Map([['I', 1], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['D', 500], ['M', 1000]]); 13 let i = s.length - 1; 14 let res = map.get(s[i]); 15 while (i > 0) { 16 let cur = map.get(s[i]); 17 let pre = map.get(s[i - 1]); 18 if (pre >= cur) { 19 res += pre; 20 } else { 21 res -= pre; 22 } 23 i--; 24 } 25 return res; 26 };
Java实现
1 class Solution { 2 public int romanToInt(String s) { 3 int sum = 0; 4 int preNum = getValue(s.charAt(0)); 5 for (int i = 1; i < s.length(); i++) { 6 int num = getValue(s.charAt(i)); 7 if (preNum < num) { 8 sum -= preNum; 9 } else { 10 sum += preNum; 11 } 12 preNum = num; 13 } 14 sum += preNum; 15 return sum; 16 } 17 18 private int getValue(char ch) { 19 switch (ch) { 20 case 'I': 21 return 1; 22 case 'V': 23 return 5; 24 case 'X': 25 return 10; 26 case 'L': 27 return 50; 28 case 'C': 29 return 100; 30 case 'D': 31 return 500; 32 case 'M': 33 return 1000; 34 default: 35 return 0; 36 } 37 } 38 }