Search code examples
javaroman-numerals

How do you find a roman numeral equivalent of an integer


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.


Solution

  • Here is a link for many languages including Java. Here's an extract of relevance:

    public class RN {
    
        enum Numeral {
            I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
            int weight;
    
            Numeral(int weight) {
                this.weight = weight;
            }
        };
    
        public static String roman(long n) {
    
            if( n <= 0) {
                throw new IllegalArgumentException();
            }
    
            StringBuilder buf = new StringBuilder();
    
            final Numeral[] values = Numeral.values();
            for (int i = values.length - 1; i >= 0; i--) {
                while (n >= values[i].weight) {
                    buf.append(values[i]);
                    n -= values[i].weight;
                }
            }
            return buf.toString();
        }
    
        public static void test(long n) {
            System.out.println(n + " = " + roman(n));
        }
    
        public static void main(String[] args) {
            test(1999);
            test(25);
            test(944);
            test(0);
        }
    
    }