romanNumeralToInt function

int romanNumeralToInt(
  1. String romanNumeral
)

Parses a Roman numeral string into its integer value.

Expects uppercase Roman numerals (I, V, X, L, C, D, M). Handles subtractive notation (e.g., 'IV' = 4, 'IX' = 9).

Throws if the string contains unrecognized characters.

Implementation

int romanNumeralToInt(String romanNumeral) {
  final romanMap = romanNumerals.map((key, value) => MapEntry(value, key));
  var i = 0;
  var result = 0;
  while (i < romanNumeral.length) {
    if (i + 1 < romanNumeral.length &&
        romanMap.containsKey(romanNumeral.substring(i, i + 2))) {
      result += romanMap[romanNumeral.substring(i, i + 2)]!;
      i += 2;
    } else {
      result += romanMap[romanNumeral[i]]!;
      i += 1;
    }
  }
  return result;
}