-
Notifications
You must be signed in to change notification settings - Fork 1
/
13_Roman to Integer_3.java
61 lines (58 loc) · 1.67 KB
/
13_Roman to Integer_3.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @author WasitShafi
* @since 15-AUG-2021
*/
class Solution {
public int romanToInt(String s) {
int ans = 0;
int n = s.length();
Map<String, Integer> romanValue = new HashMap<>();
romanValue.put("I", 1);
romanValue.put("IV", 4);
romanValue.put("V", 5);
romanValue.put("IX", 9);
romanValue.put("X", 10);
romanValue.put("XL", 40);
romanValue.put("L", 50);
romanValue.put("XC", 90);
romanValue.put("C", 100);
romanValue.put("CD", 400);
romanValue.put("D", 500);
romanValue.put("CM", 900);
romanValue.put("M", 1000);
for (int i = 0; i < n; i++) {
switch (s.charAt(i)) {
case 'I':
if (i + 1 < n && (s.charAt(i + 1) == 'V' || s.charAt(i + 1) == 'X')) {
ans += romanValue.get(s.substring(i, i++ + 2));
} else {
ans += romanValue.get(s.substring(i, i + 1));
}
break;
case 'X':
if (i + 1 < n && (s.charAt(i + 1) == 'L' || s.charAt(i + 1) == 'C')) {
ans += romanValue.get(s.substring(i, i++ +2));
} else {
ans += romanValue.get(s.substring(i, i + 1));
}
break;
case 'L':
ans += romanValue.get(s.substring(i, i + 1));
break;
case 'C':
if (i + 1 < n && (s.charAt(i + 1) == 'D' || s.charAt(i + 1) == 'M')) {
ans += romanValue.get(s.substring(i, i++ + 2));
} else {
ans += romanValue.get(s.substring(i, i + 1));
}
break;
case 'V':
case 'D':
case 'M':
ans += romanValue.get(s.substring(i, i + 1));
break;
}
}
return ans;
}
}