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)
| 40 | // outside the range 1 to 3,999 will return an error. Nil or empty string return 0 |
| 41 | // with no error thrown. |
| 42 | func 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 | } |
no outgoing calls