Java int to roman 1

Java int to roman

import java.util.TreeMap;

public class RomanNumber {

    private final static TreeMap map = new TreeMap();

    static {

        map.put(1000, "M");
        map.put(900, "CM");
        map.put(500, "D");
        map.put(400, "CD");
        map.put(100, "C");
        map.put(90, "XC");
        map.put(50, "L");
        map.put(40, "XL");
        map.put(10, "X");
        map.put(9, "IX");
        map.put(5, "V");
        map.put(4, "IV");
        map.put(1, "I");


    public final static String toRoman(int number) {
        int l =  map.floorKey(number);
        if ( number == l ) {
            return map.get(number);
        return map.get(l) + toRoman(number-l);


Here is what the above code is Doing:
1. It creates a TreeMap with the Roman numbers as keys and their corresponding Arabic numbers as values.
2. It then creates a static method toRoman() which takes an Arabic number as input and returns the corresponding Roman number.
3. It uses the floorKey() method of the TreeMap to find the largest Roman number less than or equal to the input number.
4. If the input number is equal to the largest Roman number, then the corresponding Roman number is returned.
5. If the input number is not equal to the largest Roman number, then the largest Roman number is concatenated with the Roman number corresponding to the remainder of the input number.
6. The remainder is calculated by subtracting the largest Roman number from the input number.
7. The toRoman() method is called recursively with the remainder as the input number.
8. The recursion ends when the input number is equal to the largest Roman number.

Similar Posts