|
| 1 | +package easy; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * Have the function BasicRomanNumerals(str) read str which will be a string of Roman numerals. |
| 7 | + * The numerals being used are: I for 1, V for 5, X for 10, L for 50, |
| 8 | + * C for 100, D for 500 and M for 1000. |
| 9 | + * In Roman numerals, to create a number like 11 you simply add a 1 after the 10, |
| 10 | + * so you get XI. But to create a number like 19, you use the subtraction notation |
| 11 | + * which is to add I before an X or V (or add an X before an L or C). |
| 12 | + * So 19 in Roman numerals is XIX. |
| 13 | + * --- |
| 14 | + * The goal of your program is to return the decimal equivalent of the Roman numeral given. |
| 15 | + * For example: if str is "XXIV" your program should return 24 |
| 16 | + */ |
| 17 | +public class BasicRomanNumerals { |
| 18 | + |
| 19 | + /** |
| 20 | + * Basic Roman Numerals function. |
| 21 | + * |
| 22 | + * @param str input string |
| 23 | + * @return the decimal equivalent of the Roman numeral given |
| 24 | + */ |
| 25 | + private static int basicRomanNumerals(String str) { |
| 26 | + HashMap<String, Integer> numerals = new HashMap<>(); |
| 27 | + numerals.put("M", 1000); |
| 28 | + numerals.put("D", 500); |
| 29 | + numerals.put("C", 100); |
| 30 | + numerals.put("X", 10); |
| 31 | + numerals.put("L", 50); |
| 32 | + numerals.put("V", 5); |
| 33 | + numerals.put("I", 1); |
| 34 | + // reversing the string makes the parsing easier |
| 35 | + char[] reversed = new StringBuilder(str).reverse().toString().toCharArray(); |
| 36 | + int result = 0; |
| 37 | + int prevValue = 0; |
| 38 | + for (char cr : reversed) { |
| 39 | + int thisValue = numerals.get(Character.toString(cr)); |
| 40 | + if (thisValue > prevValue) { |
| 41 | + result += thisValue; |
| 42 | + } else { |
| 43 | + result -= thisValue; |
| 44 | + } |
| 45 | + prevValue = thisValue; |
| 46 | + } |
| 47 | + return result; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Entry point. |
| 52 | + * |
| 53 | + * @param args command line arguments |
| 54 | + */ |
| 55 | + public static void main(String[] args) { |
| 56 | + var result1 = basicRomanNumerals("XXIV"); |
| 57 | + System.out.println(result1); |
| 58 | + var result2 = basicRomanNumerals("XLVI"); |
| 59 | + System.out.println(result2); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments