Roman numerals are represented by seven different symbols:
I
,V
,X
,L
,C
,D
andM
.Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000For example,
2
is written asII
in Roman numeral, just two one's added together.12
is written asXII
, which is simplyX + II
. The number27
is written asXXVII
, which isXX + 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 asIV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asIX
. 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.
Example 1:
Input: s = "III" Output: 3Example 2:
Input: s = "IV" Output: 4Example 3:
Input: s = "IX" Output: 9Example 4:
Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.Example 5:
Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.Constraints:
1 <= s.length <= 15
s
contains only the characters('I', 'V', 'X', 'L', 'C', 'D', 'M')
.- It is guaranteed that
s
is a valid roman numeral in the range[1, 3999]
.
多提供几种思路
第一种用switch语句
class Solution {
public int romanToInt(String s) {
int sum = 0;
int length = s.length();
for(int i = length - 1;i >= 0;i--){
char c = s.charAt(i);
switch(c){
sum += (sum >= 5 ? -1 : 1);
break;
case 'V' :
sum += 5;
break;
case 'X' :
sum += 10 * (sum >= 50 ? -1 : 1);
break;
case 'L' :
sum = sum + 50;
break;
case 'C' :
sum += 100 * (sum >= 500 ? -1 : 1);
break;
case 'D' :
sum = sum + 500;
break;
case 'M' :
sum = sum + 1000;
break;
default :
sum = 0;
break;
}
}
return sum;
}
}
public static int romanToInt(String s) {
if (s == null || s.length() == 0)
return -1;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
//result中存储字符串中最后一个字符所代表的数字
int len = s.length(), result = map.get(s.charAt(len - 1));
//从倒数第二个字符中的数字开始比较
for (int i = len - 2; i >= 0; i--) {
if (map.get(s.charAt(i)) >= map.get(s.charAt(i + 1)))
result += map.get(s.charAt(i));
else
result -= map.get(s.charAt(i));
}
return result;
}