forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoman-to-Integer.java
More file actions
55 lines (45 loc) · 1.05 KB
/
Roman-to-Integer.java
File metadata and controls
55 lines (45 loc) · 1.05 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
class Solution {
public int romanToInt(String s) {
int len = s.length();
int ans = 0;
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
int cur = getValue(ch);
if (i < len - 1 && cur < getValue(s.charAt(i + 1))) {
ans -= cur;
} else {
ans += cur;
}
}
return ans;
}
private int getValue(char ch) {
int ans = 0;
switch (ch) {
case 'I':
ans = 1;
break;
case 'V':
ans = 5;
break;
case 'X':
ans = 10;
break;
case 'L':
ans = 50;
break;
case 'C':
ans = 100;
break;
case 'D':
ans = 500;
break;
case 'M':
ans = 1000;
break;
default:
break;
}
return ans;
}
}