Given this chart:
I want to convert integers into their respected Roman letters. For example, let's say we have a list of integers like: [1, 49, 23]
. The method should return something like this:['I', 'XLIX', 'XXIII']
. 49 is 40 + 9 so it'll be 'XLIX'.
Here's what I wrote so far in Java:
public static List<String> romanizer(List<Integer> numbers) {
String[] romanLetters = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" };
int[] numberArray = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
ArrayList<String> result = new ArrayList<>();
int times = 0;
for (int h = numberArray.length - 1; h >= 0; h--) {
for (int d = 0; d < numbers.size(); d++) {
times = numbers.get(d) / numberArray[h];
numbers.set(d, numbers.get(d) % numberArray[h]);
}
while (times > 0) {
result.add(romanLetters[h]);
times--;
}
}
return result;
}
But I got something like this instead: [X, X, I, I, I]
. Anyone can help/see the issue?
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;
}