Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
給定一個羅馬數字,把它轉換成一個整數。
把羅馬數字字符串轉換成字符數組先,如下表,每個數字僅對應一個字符,而且字符不一樣。故可從頭開始取值進行對應。
The Roman Symbols
The Romans used a special method of showing numbers, based on the following symbols:
1
5
10
50
100
500
1000
I
V
X
L
C
D
M
public int romanToInt(String s) {
Map romans = new HashMap();
romans.put('I', 1);
romans.put('V', 5);
romans.put('X', 10);
romans.put('L', 50);
romans.put('C', 100);
romans.put('D', 500);
romans.put('M', 1000);
char[] ch = s.toCharArray();
int num = 0, val = 0;
for (int i = 0; i < ch.length; i++) {
val = romans.get(ch[i]);
if (i == ch.length - 1 || romans.get(ch[i + 1]) <= val)
num += val;
else
num -= val;
}
return num;
}