Converting Integers to Roman Numerals - Java

Converting integers to their roman numeral equivalents

To minimize confusion, I suggest making two function instead of one:

private static final String[] ROMAN_LETTERS = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM",  "M" };
private static final int[] ROMAN_NUMBERS = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };

public static String romanizer(int num) {
StringBuilder result = new StringBuilder();
for (int h = ROMAN_NUMBERS.length - 1; h >= 0; h--) {
result.append(ROMAN_LETTERS[h].repeat(num / ROMAN_NUMBERS[h]));
num = num % ROMAN_NUMBERS[h];
}
return result.toString();
}

public static List<String> romanizer(List<Integer> numbers) {
List<String> result = new ArrayList<>();
for (int num : numbers)
result.add(romanizer(num));
return result;
}

Converting integers into words and roman numerals

Take a look at cl-format, it can return "twenty one", I used that for project euler.

http://clojuredocs.org/clojure_core/1.2.0/clojure.pprint/cl-format

and Roman too:

~@R prints arg as a Roman numeral: IV; and ~:@R prints arg as an old Roman numeral: IIII.

Sorting roman numeral in java

You can use the Comparator util class to compare by the actual numeral value:

static void sortRomanNumerals(List<String> romanNumerals){
romanNumerals.sort(Comparator.comparing(Main::romanToDecimal));
}


Related Topics



Leave a reply



Submit