-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0013. Roman to Integer
63 lines (62 loc) · 1.74 KB
/
0013. Roman to Integer
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
62
63
class Solution {
// public int romanToInt(String s) {
// HashMap<Character, Integer> map = new HashMap<>();
// 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);
// int len = s.length();
// int last = 0;
// int sum = 0;
// for (int i = len - 1; i > - 1; i--) {
// int curr = map.get(s.charAt(i));
// sum += (curr < last ? - 1 * curr : curr);
// last = curr;
// }
// return sum;
// }
public int romanToInt(String s) {
int len = s.length();
int last = 0;
int sum = 0;
for (int i = len - 1; i > - 1; i--) {
int curr = 0;
switch (s.charAt(i)) {
case 'I': {
curr = 1;
break;
}
case 'V': {
curr = 5;
break;
}
case 'X': {
curr = 10;
break;
}
case 'L': {
curr = 50;
break;
}
case 'C': {
curr = 100;
break;
}
case 'D': {
curr = 500;
break;
}
case 'M': {
curr = 1000;
break;
}
}
sum += (curr < last ? - 1 * curr : curr);
last = curr;
}
return sum;
}
}