Convert Roman Numeral to Integer and Vice Versa

This post will explore the situations where there is a need to convert a roman numeral to integer and vice versa. The common basic symbols in the roman numeral system are I (=1), V (=5), X (=10), L (=50), C (=100), D (=500), and M (=1000). The following table lists the first 100 numbers and the roman numeral expression of those numbers.

roman-numeral-table.jpg

Roman Numeral to Integer

We will start with the algorithm that converts roman numeral to integer. The pattern to take away is that the left place value is generally greater than or equal to the current place value. Once in a while, the left place value is less than the current place value, see 4, 9, 14, 19, etc. In these situations, the idea is to subtract the left place value from the current place value and the difference will be the integer value of the combined place values. The approach is to iterate over the roman numeral while keeping a current and previous pointers. Then add current value to the output per iteration for the first case and subtract the previous value for the second case.

Implementation

public static int toInt(String romanNumeral) {
    Map<Character, Integer> map = new HashMap<Character, Integer>() {{
        put('I', 1);
        put('V', 5);
        put('X', 10);
        put('L', 50);
        put('C', 100);
        put('D', 500);
        put('M', 1000);
    }};
    int out = map.get(romanNumeral.charAt(0));

    for(int i = 1; i < romanNumeral.length(); i++) {
        int cur = map.get(romanNumeral.get(i));
        int prev = map.get(romanNumeral.get(i - 1));
        out += (cur > prev) ? -prev + (cur - prev) : cur;
    }

    return out;
}

Integer to Roman Numeral

The second part of this post is to convert a given integer to roman numeral. The idea is to keep appending current roman numeral symbol to the output, as long as the difference between the input and current roman numeral value is greater than or equal to zero. Once the difference is less than zero, use the next roman numeral symbol.

Implementation

public static String toRomanNumeral(int x) {
    Map<Integer, Character> map = new LinkedHashMap<Integer, Character>() {{
        put(1000, 'M');
        put(500, 'D');
        put(100, 'C');
        put(50, 'L');
        put(10, 'X');
        put(5, 'V');
        put(1, 'I');
    }};

    StringBuilder sb = new StringBuilder();
    Iterator it<Integer> = map.keySet().iterator();
    int cur = it.next();

    while(it.hasNext() && x > 0) {
        if(x - cur < 0)
            cur = it.next();
        else {
            sb.append(map.get(cur));
            x -= cur;
        }
    }

    return sb.toString();
}

This article is my 29th oldest. It is 407 words long, and it’s got 0 comments for now.