I had reason to write a Roman Numeral parser - the spec was simple - pass in the number as a Roman Numeral, which I take as a String, for instance, "MCMLXXXIV", and return the decimal equivalent.
It took me a few minutes to work out a neat way of doing that, so I thought I'd share in case anyone else needs it. It doesn't check the numerals are valid, and comes without warranty, blah, blah, but it works for all my tests. It's in Java, but would be easy to convert to any other language
There's the class Parser which does the work, and the RomanNumeral enum which stores the values for each letter. There's not much error handling either.
Enjoy!
public class Parser {
public static int parse(String romanNumerals) {
int[] values = new int[romanNumerals.length()];
for (int i = 0; i < romanNumerals.length(); i++) {
values[i] = RomanNumeral.valueOf("" + romanNumerals.charAt(i)).value();
}
return parse(values);
}
public static int parse(int... values) {
int total = 0;
int subtraction = 0;
for (int idx = 0; idx < values.length - 1; idx++) {
if (values[idx] < values[idx + 1]) {
subtraction = values[idx];
}
else {
total += (values[idx] - subtraction);
subtraction = 0;
}
}
total += (values[values.length - 1] - subtraction);
return total;
}
private Parser() {}
}
public enum RomanNumeral {
I (1),
V (5),
X (10),
L (50),
C (100),
D (500),
M (1000);
private int value;
private RomanNumeral(int value) {
this.value = value;
}
public int value() {
return value;
}
}
No comments:
Post a Comment