1

Given this chart:

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?

Fire Assassin
  • 59
  • 1
  • 8
  • 3
    You should start by separating the problem into two. 1. How to convert a single number to a single roman string. 2. How to convert a list of numbers to a list of roman strings. (Hint: You should end up with two methods.) – Clashsoft Jul 17 '21 at 23:57
  • Does this answer your question? [Converting Integers to Roman Numerals - Java](https://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java) – tevemadar Jul 18 '21 at 00:01
  • Ahhhh i get it, basically converting a single number to a single roman string should be the helper method for this? – Fire Assassin Jul 18 '21 at 00:03
  • Not exactly an answer to your question, but for a very elegant solution to this problem, see the top voted answer at https://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java/#19759564 – GreyBeardedGeek Jul 18 '21 at 00:12

1 Answers1

4

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;
}
Ofek
  • 1,065
  • 6
  • 19