1+ // AUTHOR : Sagar Wadhwa
2+ class Solution {
3+ public int romanToInt (String s ) {
4+ // Hashmap in java which stores key value pairs. Each key is unique and no key is repeated
5+ HashMap <Character ,Integer > map = new HashMap <>();
6+
7+ // Defining the basic rules of mapping from roman numeral to integer numbers.
8+ map .put ('I' ,1 );
9+ map .put ('V' ,5 );
10+ map .put ('X' ,10 );
11+ map .put ('L' ,50 );
12+ map .put ('C' ,100 );
13+ map .put ('D' ,500 );
14+ map .put ('M' ,1000 );
15+
16+ //extract the last character of the string, and find it in the map, store this keys value in the
17+ // variable named "res"
18+ int res = map .get (s .charAt (s .length ()-1 ));
19+
20+ //iterate over the string from the second last character till the first character. Idea to solve
21+ // this problem is that in the loop, for every character we check whether the value of the roman
22+ // numeral at the i+1 th index is greater than or less than the value of the roman numeral at i th
23+ // index. If the value of the roman numeral at the i th index is less than the value of the
24+ // roman numeral at i+1 th index, then obviously that means we have to subtract the value of the
25+ // roman numeral at the i th index from the result calculated so far. Else we have to add the value
26+ // of the roman numeral at the i th index to the result calculated so far. Example: V means five,
27+ // but if it is IV, then here the value of the roman numeral I is less than the value of the roman
28+ // numeral V, so that means subtract I from V (4). If the string is VI, means 6, then here the value of
29+ // V is greater than the value of I, so add I in V, that is 6.
30+ // Doing so in an iterative fashion and storing the result and then adding or subtracting values
31+ // from it accordingly will give us our final result.
32+ for (int i =s .length ()-2 ;i >=0 ;i --){
33+
34+ if (map .get (s .charAt (i )) < map .get (s .charAt (i +1 ))){
35+ res -= map .get (s .charAt (i ));
36+ }else {
37+ res += map .get (s .charAt (i ));
38+ }
39+ }
40+ return res ;
41+ }
42+ }
0 commit comments