How do you find a roman numeral equivalent of an integer

Viewed 8523

How do you find a roman numeral equivalent of an integer. Is there a java library which provides this capability?

I did find a similar question, but I would prefer an out of the box API abstraction for this issue. Its just painful to handle all possible combinations in your code.

4 Answers

My version uses unmodified lookup and is more explicit.

 public String numToRoman(int num) {
    int numLength = (int) (Math.log10(num) + 1);
    int place_value = 10;
    final Map<Integer, char[]> romanModeLookup = new HashMap<>();
    romanModeLookup.putAll(Map.of(10, new char[]{'I', 'V', 'X'}, 100, new char[]{'X', 'L', 'C'},
            1000, new char[]{'C', 'D', 'M'}, 10000, new char[]{'M'}));


    final StringBuilder romanBuilder = new StringBuilder();
    while (numLength > 0) {
        numLength--;
        int current_num_at_place_val = (num % place_value) / (place_value / 10);
        System.out.println(current_num_at_place_val);

        if (place_value < 10000) {
            if (current_num_at_place_val == 9) {
                romanBuilder.append(romanModeLookup.get(place_value)[2]).append(romanModeLookup.get(place_value)[0]);
            } else if (current_num_at_place_val >= 5) {
                int remaining_sticks = current_num_at_place_val - 5;
                while (remaining_sticks > 0) {
                    romanBuilder.append(romanModeLookup.get(place_value)[0]);
                    remaining_sticks--;
                }
                romanBuilder.append(romanModeLookup.get(place_value)[1]);

            } else if (current_num_at_place_val == 4) {
                romanBuilder.append(romanModeLookup.get(place_value)[1]).append(romanModeLookup.get(place_value)[0]);
            } else {
                while (current_num_at_place_val > 0) {
                    romanBuilder.append(romanModeLookup.get(place_value)[0]);
                    current_num_at_place_val--;
                }
            }
        } else if (place_value == 10000) {
            while (current_num_at_place_val > 0) {
                romanBuilder.append(romanModeLookup.get(10000)[0]);
                current_num_at_place_val--;
            }
        } else {
            throw new IllegalArgumentException("Number too big for Romanization");
        }
        place_value *= 10;
    }

    return romanBuilder.reverse().toString();}
Related