πŸ› οΈToolsShed

Roman Numeral Converter

Convert between Arabic numbers and Roman numerals instantly.

Quick Reference
I= 1
V= 5
X= 10
L= 50
C= 100
D= 500
M= 1000

Frequently Asked Questions

Code Implementation

ROMAN_VALS = [
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
    (100,  "C"), (90,  "XC"), (50,  "L"), (40,  "XL"),
    (10,   "X"), (9,   "IX"), (5,   "V"), (4,   "IV"), (1, "I"),
]

def to_roman(n: int) -> str:
    if not 1 <= n <= 3999:
        raise ValueError("n must be between 1 and 3999")
    result = ""
    for value, numeral in ROMAN_VALS:
        while n >= value:
            result += numeral
            n -= value
    return result

def from_roman(s: str) -> int:
    roman_map = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
    s = s.upper()
    total, prev = 0, 0
    for ch in reversed(s):
        val = roman_map[ch]
        total += val if val >= prev else -val
        prev = val
    return total

print(to_roman(2024))     # MMXXIV
print(to_roman(1999))     # MCMXCIX
print(from_roman("XIV"))  # 14
print(from_roman("XLII")) # 42

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.