How to convert Romain numbers to integers in Java

Romain numeral were used by the ancient Rome. The are composed of seven characters from the latin alphabet: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500 and M is 1000. The numeral is the sum of all the characters and is written from the highest number to the lowest. There is an exception, if a smaller number is written before the current number, it's value is removed from the second one. For example, the romain number IV is 5 as the character I is smaller that V and is written first.

The algorithm to convert the romain number parses the String from the last character adds it to the sum and keeps the previous character. If the current character is less than the previous one it is removed from the sum. The sum is returned in output.

Create the following java file:

public class RomainNumbers {
    enum RN {
        I(1), V(5), X(10), L(50), C(100), D(50), M(1000);

        int nb;

        RN(int i) {
            this.nb = i;
        }
    }

    public static int convertROMNumber(String input) {
        int i = input.length() - 1;
        int previous = 0;
        int toReturn = 0;
        while (i >= 0) {
            char c = input.charAt(i);
            int currentValue = RN.valueOf(String.valueOf(c)).nb;

            if (currentValue < previous)
                toReturn -= currentValue;
            else
                toReturn += currentValue;

            previous = currentValue;
            i--;
        }

        return toReturn;
    }

    public static void main(String[] args) {
        String[] tab = {"III", "IV", "VI", "XIV"};
        for (String current : tab) {
            System.out.println(current + " => " + convertROMNumber(current));
        }
    }

}

The output will be:

III => 3
IV => 4
VI => 6
XIV => 14

By starting from the end of the String and keeping the previous character, we don't need to keep testing the next character for every character.

References:

Roman numerals

Recent Comments