View Javadoc
1   package epam.roman;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   import java.util.function.ToIntFunction;
6   
7   /**
8    * A converter that converts Roman numerals to Arabic integers.
9    */
10  public final class RomanToArabicConverter implements ToIntFunction<String> {
11  
12      private static final Map<Character, Integer> ROMAN_TO_ARABIC_MAP = new HashMap<>();
13  
14      static {
15          ROMAN_TO_ARABIC_MAP.put('I', 1);
16          ROMAN_TO_ARABIC_MAP.put('V', 5);
17          ROMAN_TO_ARABIC_MAP.put('X', 10);
18          ROMAN_TO_ARABIC_MAP.put('L', 50);
19          ROMAN_TO_ARABIC_MAP.put('C', 100);
20          ROMAN_TO_ARABIC_MAP.put('D', 500);
21          ROMAN_TO_ARABIC_MAP.put('M', 1000);
22      }
23  
24      /**
25       * Converts a Roman numeral string to an Arabic integer.
26       *
27       * @param roman the Roman numeral string to be converted
28       * @return the Arabic integer representation of the Roman numeral
29       */
30      @Override
31      public int applyAsInt(String roman) {
32          int result = 0;
33          int prevValue = 0;
34  
35          for (int i = roman.length() - 1; i >= 0; i--) {
36              char currentChar = roman.charAt(i);
37              int currentValue = ROMAN_TO_ARABIC_MAP.get(currentChar);
38  
39              if (currentValue < prevValue) {
40                  result -= currentValue;
41              } else {
42                  result += currentValue;
43              }
44  
45              prevValue = currentValue;
46          }
47  
48          return result;
49      }
50  }