TheAlgorithms/Go · error

invalid roman numeral

Error message

invalid roman numeral

What it means

RomanToInt consumes the input by repeatedly stripping known numeral prefixes (CM, M, CD...). If characters remain after all prefixes are tried, the string used symbols that don't form a valid roman numeral (e.g. 'IIII' isn't matched only in some cases, or garbage like 'XYZ').

Source

Thrown at conversion/romantoint.go:56

// RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers
// outside the range 1 to 3,999 will return an error. Nil or empty string return 0
// with no error thrown.
func RomanToInt(input string) (int, error) {
	if input == "" {
		return 0, nil
	}
	var output int
	for _, n := range nums {
		for strings.HasPrefix(input, n.sym) {
			output += n.val
			input = input[len(n.sym):]
		}
	}
	// if we are still left with input string values then the
	// input was invalid and an error is returned.
	if len(input) > 0 {
		return 0, errors.New("invalid roman numeral")
	}
	return output, nil
}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Validate/normalize the roman numeral string before calling RomanToInt
  2. Trim whitespace and ensure uppercase letters only
  3. Report the malformed input to the user with the offending string
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at conversion/romantoint.go:56 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/54d101de510a5f5d. Report an issue: GitHub.