Java program: Convert to Roman Numerals


import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class RomanNumerals {

    private static Map<Integer, String> map;

    static {
        map = new LinkedHashMap<>();
        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 static void main(String[] args) {
            System.out.println(getRomanNumeral(451));
            System.out.println(getRomanNumeral(174));
    }

    private static String getRomanNumeral(int input) {
        String result = "";
        while (input > 0) {
            Iterator<Integer> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                int temp = iterator.next();
                if (input - temp >= 0) {
                    result = result + map.get(temp);
                    input = input - temp;
                    break;
                }
            }
        }
        return result;
    }
}

Advertisements
This entry was posted in java and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s