easy +10 pts

Roman to Integer

Convert a Roman numeral string to its integer value.

Write a function `roman_to_int(s: str) -> int` that takes a string `s` representing a valid Roman numeral and returns its integer value. The Roman numerals use the characters I, V, X, L, C, D, M with values 1, 5, 10, 50, 100, 500, 1000. The numeral is written in standard form: numerals are usually written from largest to smallest from left to right, except when a smaller numeral precedes a larger one to indicate subtraction (e.g., IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900). The input will always be a valid Roman numeral in the range 1 to 3999. You may assume the input is non-empty and contains only these characters.

Constraints

Input length is between 1 and 15. The numeral is valid and represents an integer between 1 and 3999.

Example

>>> roman_to_int('III')
3
>>> roman_to_int('LVIII')
58
>>> roman_to_int('MCMXCIV')
1994
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Map each Roman character to its value.
Iterate left to right. If the current value is less than the next value, subtract it; otherwise add it.
Alternatively, scan from right to left: add if current value is >= previous, subtract otherwise.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.