@@ -57,13 +57,63 @@ private static void initializeMap(HashMap<String, Integer> map) {
5757 map .put ("CM" , 900 );
5858 }
5959
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" ));
60+ // optimal approach
61+ public static int romanToInt2 (String s ) throws Exception {
62+ int ans = 0 ;
63+ int len = s .length ();
64+
65+ for (int i = 0 ; i < len - 1 ; i ++) {
66+
67+ int currValue = getRomanValue (s .charAt (i ));
68+ int nextValue = getRomanValue (s .charAt (i + 1 ));
69+
70+ if (currValue == -1 || nextValue == -1 ) {
71+ throw new Exception ("Invalid character found..." );
72+ }
73+
74+ if (currValue < nextValue ) {
75+ ans -= currValue ;
76+ } else {
77+ ans += currValue ;
78+ }
79+ }
80+
81+ int lastCharValue = getRomanValue (s .charAt (len - 1 ));
82+
83+ return ans + lastCharValue ;
84+ }
85+
86+ private static int getRomanValue (char next ) {
87+ switch (next ) {
88+ case 'I' :
89+ return 1 ;
90+ case 'V' :
91+ return 5 ;
92+ case 'X' :
93+ return 10 ;
94+ case 'L' :
95+ return 50 ;
96+ case 'C' :
97+ return 100 ;
98+ case 'D' :
99+ return 500 ;
100+ case 'M' :
101+ return 1000 ;
102+ }
103+ return -1 ;
104+ }
105+
106+ public static void main (String [] args ) throws Exception {
107+ // System.out.println(romanToInt("III"));
108+ // System.out.println(romanToInt("IV"));
109+ // System.out.println(romanToInt("IX"));
110+ // System.out.println(romanToInt("LVIII"));
111+ // System.out.println(romanToInt("MCMXCIV"));
112+ System .out .println (romanToInt2 ("MDCXCV" ));
113+
114+ System .out .println (romanToInt2 ("IV" ));
115+
116+ // System.out.println(getRomanValue('M'));
67117
68118 /*
69119 * testing character concatenation
0 commit comments