-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
69 lines (65 loc) · 1.62 KB
/
Copy pathSolution.java
File metadata and controls
69 lines (65 loc) · 1.62 KB
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
64
65
66
67
68
69
class Solution {
public int romanToInt(String s) {
int sum = 0;
int cur = 0;
// step 1 converting first character directly
switch (s.charAt(0)) {
case 'I':
cur = 1;
break;
case 'V':
cur = 5;
break;
case 'X':
cur = 10;
break;
case 'L':
cur = 50;
break;
case 'C':
cur = 100;
break;
case 'D':
cur = 500;
break;
case 'M':
cur = 1000;
break;
}
for (int i = 1; i < s.length(); i++) {
int next = 0;
switch (s.charAt(i)) {
case 'I':
next = 1;
break;
case 'V':
next = 5;
break;
case 'X':
next = 10;
break;
case 'L':
next = 50;
break;
case 'C':
next = 100;
break;
case 'D':
next = 500;
break;
case 'M':
next = 1000;
break;
}
// comparing current and the next
if (cur < next) {
sum -= cur;
} else {
sum += cur;
}
cur = next;
}
sum += cur;
return sum;
}
}