File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ package MustDoEasyList ;
2+
3+ import java .util .HashMap ;
4+
5+ public class RomanToInteger13 {
6+
7+ public static int romanToInt (String s ) {
8+
9+ HashMap <String , Integer > map = new HashMap <>();
10+ initializeMap (map );
11+
12+ int len = s .length ();
13+ int idx = 0 ;
14+ int sum = 0 ;
15+ char ch1 , ch2 ;
16+ // parse string
17+ while (idx < len ) {
18+ ch1 = ' ' ;
19+ ch2 = ' ' ;
20+
21+ ch1 = s .charAt (idx );
22+
23+ if ((idx + 1 ) < len )
24+ ch2 = s .charAt (idx + 1 );
25+
26+ if (ch2 != ' ' && map .get ("" + ch1 ) < map .get ("" + ch2 )) {
27+ // if first character is small than next char
28+ String currCombination = "" + ch1 + ch2 ;
29+ sum += map .get (currCombination );
30+ idx += 2 ; // two characters are combined so +2 in index
31+
32+ } else {
33+ // considering only one Roman character
34+ sum += map .get ("" + ch1 );
35+ idx ++;
36+ }
37+ }
38+
39+ return sum ;
40+ }
41+
42+ private static void initializeMap (HashMap <String , Integer > map ) {
43+
44+ map .put ("I" , 1 );
45+ map .put ("V" , 5 );
46+ map .put ("X" , 10 );
47+ map .put ("L" , 50 );
48+ map .put ("C" , 100 );
49+ map .put ("D" , 500 );
50+ map .put ("M" , 1000 );
51+ // special cases
52+ map .put ("IV" , 4 );
53+ map .put ("IX" , 9 );
54+ map .put ("XL" , 40 );
55+ map .put ("XC" , 90 );
56+ map .put ("CD" , 400 );
57+ map .put ("CM" , 900 );
58+ }
59+
60+ public static void main (String [] args ) {
61+ System .out .println (romanToInt ("III" ));
62+ System .out .println (romanToInt ("IV" ));
63+ System .out .println (romanToInt ("IX" ));
64+ System .out .println (romanToInt ("LVIII" ));
65+ System .out .println (romanToInt ("MCMXCIV" ));
66+ System .out .println (romanToInt ("MDCXCV" ));
67+
68+ /*
69+ * testing character concatenation
70+ *
71+ * System.out.println("" + 'c' + 'd');
72+ */
73+ }
74+ }
You can’t perform that action at this time.
0 commit comments