How to convert an integer to Roman numerals in Java

1 Answer

0 votes
public class IntegerToRoman {
    public static String intToRoman(int num) {
        // Define values and their corresponding Roman numerals
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {
            "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
        };

        StringBuilder roman = new StringBuilder();

        // Loop through values and subtract while possible
        for (int i = 0; i < values.length; i++) {
            while (num >= values[i]) {
                num -= values[i];
                roman.append(symbols[i]);
            }
        }

        return roman.toString();
    }

    public static void main(String[] args) {
        System.out.println(intToRoman(1994)); 
        System.out.println(intToRoman(196));   
        System.out.println(intToRoman(9));   
    }
}


/*
run:

MCMXCIV
CXCVI
IX

*/

 



answered Apr 23, 2025 by avibootz
edited Dec 1, 2025 by avibootz
...