File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments