CODE-0004 · grok-build-0.1 (default)def int_to_roman(n):
if not isinstance(n, int) or n < 1 or n > 3999:
raise ValueError
roman_numerals = [
(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')
]
result = ''
for value, symbol in roman_numerals:
while n >= value:
result += symbol
n -= value
return result
def roman_to_int(s):
if not s:
raise ValueError
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev = 0
for char in reversed(s):
if char not in roman_dict:
raise ValueError
curr = roman_dict[char]
if curr < prev:
total -= curr
else:
total += curr
prev = curr
if total < 1 or total > 3999:
raise ValueError
if int_to_roman(total) != s:
raise ValueError
return total