Skip to content

Commit 8bd9987

Browse files
committed
Add java solution for 13
1 parent 825d17a commit 8bd9987

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

java/_013RomanToInteger.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* Created by drfish on 25/06/2017.
6+
*/
7+
public class _013RomanToInteger {
8+
public int romanToInt(String s) {
9+
Map<Character, Integer> map = new HashMap<Character, Integer>() {{
10+
put('M', 1000);
11+
put('D', 500);
12+
put('C', 100);
13+
put('L', 50);
14+
put('X', 10);
15+
put('V', 5);
16+
put('I', 1);
17+
}};
18+
int result = 0;
19+
for (int i = 0; i < s.length(); i++) {
20+
if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {
21+
result -= map.get(s.charAt(i - 1));
22+
result += map.get(s.charAt(i)) - map.get(s.charAt(i - 1));
23+
} else {
24+
result += map.get(s.charAt(i));
25+
}
26+
}
27+
return result;
28+
}
29+
30+
public static void main(String[] args) {
31+
_013RomanToInteger solution = new _013RomanToInteger();
32+
assert 12 == solution.romanToInt("XII");
33+
assert 21 == solution.romanToInt("XXI");
34+
assert 99 == solution.romanToInt("XCIX");
35+
}
36+
}

0 commit comments

Comments
 (0)