1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| class Solution {
private class RomanInt {
public String roman;
public int integer;
public RomanInt(String roman, int integer) {
this.roman = roman;
this.integer = integer;
}
}
public int romanToInt(String s) {
RomanInt[] romanIntArry = new RomanInt[13];
romanIntArry[0] = new RomanInt("M", 1000);
romanIntArry[1] = new RomanInt("CM", 900);
romanIntArry[2] = new RomanInt("D", 500);
romanIntArry[3] = new RomanInt("CD", 400);
romanIntArry[4] = new RomanInt("C", 100);
romanIntArry[5] = new RomanInt("XC", 90);
romanIntArry[6] = new RomanInt("L", 50);
romanIntArry[7] = new RomanInt("XL", 40);
romanIntArry[8] = new RomanInt("X", 10);
romanIntArry[9] = new RomanInt("IX", 9);
romanIntArry[10] = new RomanInt("V", 5);
romanIntArry[11] = new RomanInt("IV", 4);
romanIntArry[12] = new RomanInt("I", 1);
int result = 0;
while (s.length() > 0) {
for (int i = 0; i < romanIntArry.length; i++) {
if (s.startsWith(romanIntArry[i].roman)) {
result += romanIntArry[i].integer;
s = s.replaceFirst("^"+romanIntArry[i].roman, "");
break;
}
}
}
return result;
}
}
|