CODE-0004 · grok-4.5 (medium)def int_to_roman(n):
if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n > 3999:
raise ValueError("Integer must be in range 1..3999")
mapping = [
(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"),
]
parts = []
for value, symbol in mapping:
count, n = divmod(n, value)
if count:
parts.append(symbol * count)
return "".join(parts)
def roman_to_int(s):
if not isinstance(s, str) or not s:
raise ValueError("Invalid Roman numeral")
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
total = 0
prev = 0
for ch in reversed(s):
if ch not in values:
raise ValueError("Invalid Roman numeral")
val = values[ch]
if val < prev:
total -= val
else:
total += val
prev = val
if total < 1 or total > 3999 or int_to_roman(total) != s:
raise ValueError("Invalid Roman numeral")
return total