MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / RomanToInt

Function RomanToInt

conversion/romantoint.go:42–59  ·  view source on GitHub ↗

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.

(input string)

Source from the content-addressed store, hash-verified

40// outside the range 1 to 3,999 will return an error. Nil or empty string return 0
41// with no error thrown.
42func RomanToInt(input string) (int, error) {
43 if input == "" {
44 return 0, nil
45 }
46 var output int
47 for _, n := range nums {
48 for strings.HasPrefix(input, n.sym) {
49 output += n.val
50 input = input[len(n.sym):]
51 }
52 }
53 // if we are still left with input string values then the
54 // input was invalid and an error is returned.
55 if len(input) > 0 {
56 return 0, errors.New("invalid roman numeral")
57 }
58 return output, nil
59}

Callers 2

TestRomanToIntFunction · 0.85
BenchmarkRomanToIntFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestRomanToIntFunction · 0.68
BenchmarkRomanToIntFunction · 0.68