LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>
(roman: str)
| 16 | |
| 17 | |
| 18 | def roman_to_int(roman: str) -> int: |
| 19 | """ |
| 20 | LeetCode No. 13 Roman to Integer |
| 21 | Given a roman numeral, convert it to an integer. |
| 22 | Input is guaranteed to be within the range from 1 to 3999. |
| 23 | https://en.wikipedia.org/wiki/Roman_numerals |
| 24 | >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} |
| 25 | >>> all(roman_to_int(key) == value for key, value in tests.items()) |
| 26 | True |
| 27 | """ |
| 28 | vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} |
| 29 | total = 0 |
| 30 | place = 0 |
| 31 | while place < len(roman): |
| 32 | if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): |
| 33 | total += vals[roman[place + 1]] - vals[roman[place]] |
| 34 | place += 2 |
| 35 | else: |
| 36 | total += vals[roman[place]] |
| 37 | place += 1 |
| 38 | return total |
| 39 | |
| 40 | |
| 41 | def int_to_roman(number: int) -> str: |
nothing calls this directly
no outgoing calls
no test coverage detected