-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
49 lines (43 loc) · 1.26 KB
/
Solution.java
File metadata and controls
49 lines (43 loc) · 1.26 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
public class Solution {
public int romanToInt(String s) {
if (s == null)
return 0;
int currentValue = 0;
int result = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char currentChar = s.charAt(i);
int preValue = currentValue;
switch (currentChar) {
case 'I':
currentValue = 1;
break;
case 'V':
currentValue = 5;
break;
case 'X':
currentValue = 10;
break;
case 'L':
currentValue = 50;
break;
case 'C':
currentValue = 100;
break;
case 'D':
currentValue = 500;
break;
case 'M':
currentValue = 1000;
break;
default:
return 0;
}
if (preValue > currentValue) {
result -= currentValue;
} else {
result += currentValue;
}
}
return result;
}
}