-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoman to integer
More file actions
36 lines (35 loc) · 1.04 KB
/
Roman to integer
File metadata and controls
36 lines (35 loc) · 1.04 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
public class Solution {
public int romanToInt(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(s.length() == 0) return 0;
HashMap<Character, Integer> roman = new HashMap<Character, Integer>();
roman.put('I',1);
roman.put('V',5);
roman.put('X',10);
roman.put('L',50);
roman.put('C',100);
roman.put('D',500);
roman.put('M',1000);
int res = 0, i = 0;
while (i<s.length()) {
switch(s.charAt(i)) {
case 'C':
case 'X':
case 'I':
if (i+1 < s.length()
&& roman.get(s.charAt(i+1)) > roman.get(s.charAt(i))) {
res += (roman.get(s.charAt(i+1)) - roman.get(s.charAt(i)));
i += 2;
} else {
res += roman.get(s.charAt(i));
++i;
}
break;
default:
res += roman.get(s.charAt(i));
++i;
}
}
return res;
}
}