toDecimal static method
Converts a Roman numeral string to its integer (decimal) representation.
This algorithm iterates through the Roman numeral string from left to right. At each step, it tries to match the longest possible Roman symbol (either a single character or a two-character subtractive case like "IV" or "CM") from its predefined list of symbols. Once a match is found, its decimal value is added to the total, and the string index is advanced by the length of the matched symbol.
Parameters:
romanNumeral: The Roman numeral string to convert. Case-insensitive.
Returns:
An int representing the decimal value of the Roman numeral.
Throws:
FormatException: If the input string contains invalid Roman numeral characters
Implementation
static int toDecimal(String romanNumeral) {
var totalDecimal = 0;
var i = 0;
romanNumeral = romanNumeral.toUpperCase();
while (i < romanNumeral.length) {
var matched = false;
for (int j = 0; j < _romanSymbols.length; j++) {
var currentRomanSymbol = _romanSymbols[j];
var currentDecimalValue = _decimalValues[j];
if (i + currentRomanSymbol.length <= romanNumeral.length &&
romanNumeral.substring(i, i + currentRomanSymbol.length) ==
currentRomanSymbol) {
totalDecimal += currentDecimalValue;
i += currentRomanSymbol.length;
matched = true;
break;
}
}
if (!matched) {
throw FormatException(
'Invalid Roman numeral character or sequence: '
'${romanNumeral.substring(i, i + 1)} at index $i',
);
}
}
return totalDecimal;
}