File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ public class RomanToInteger {
3+
4+ /*
5+ This function convert Roman number into Integer
6+ @param A is Roman number string
7+ */
8+ public static int romanToInt (String A ) {
9+ Map <Character , Integer > map = new HashMap <>();
10+ map .put ('I' , 1 );
11+ map .put ('V' , 5 );
12+ map .put ('X' , 10 );
13+ map .put ('L' , 50 );
14+ map .put ('C' , 100 );
15+ map .put ('D' , 500 );
16+ map .put ('M' , 1000 );
17+
18+ char c = A .charAt (A .length ()-1 );
19+ char prev = ' ' ;
20+
21+ int sum =0 ;
22+
23+ int newPrev = 0 , currentNum =0 ;
24+ for (int i = A .length () -1 ;i >=0 ;i --)
25+ {
26+ c = A .charAt (i );
27+
28+
29+ if (prev != ' ' ) {
30+ //checking current Number greater then previous or not
31+ newPrev = map .get (prev ) > newPrev ? map .get (prev ) : newPrev ;
32+ }
33+
34+
35+ currentNum = map .get (c );
36+
37+ if (currentNum >= newPrev ) //if current number greater then prev max previous then add
38+ {
39+ sum += currentNum ;
40+ }
41+ else {
42+
43+ sum -= currentNum ; // subtract upcoming number until upcoming number not greater then prev max
44+ }
45+
46+ prev = c ;
47+ }
48+
49+ return sum ;
50+ }
51+
52+
53+ public static void main (String [] args ) {
54+
55+
56+ int sum = romanToInt ("MDCCCIV" ) ;
57+ System .out .println (sum );
58+ }
59+
60+ }
You can’t perform that action at this time.
0 commit comments