toRoman static method

String toRoman(
  1. int n
)

Converts a given integer (decimal number) to its Roman numeral representation.

This algorithm uses a greedy approach by iterating through the predefined lists of Roman numeral values in descending order. It repeatedly appends the Roman symbol corresponding to the largest possible value that can be subtracted from the current decimal number until the number becomes zero.

Parameters:

  • n: The integer to convert. Valid range is typically 1 to 3999.

Returns: A String representing the Roman numeral.

Throws:

  • ArgumentError: If the input n is outside the valid range (currently 1 to 3999).

Implementation

static String toRoman(int n) {
  if (n < 1 || n > 3999) {
    throw ArgumentError(
      'Number must be between 1 and 3999 for standard Roman numerals.',
    );
  }

  final romanNumeral = StringBuffer();
  var temp = n;

  for (int i = 0; i < _decimalValues.length; i++) {
    while (temp >= _decimalValues[i]) {
      romanNumeral.write(_decimalValues[i]);
      temp -= _decimalValues[i];
    }
  }
  return romanNumeral.toString();
}