Skip to content

Instantly share code, notes, and snippets.

@benmatselby
Created January 6, 2026 14:12
Show Gist options
  • Select an option

  • Save benmatselby/31728e8cce6b75eb36646c2a7d9ebec8 to your computer and use it in GitHub Desktop.

Select an option

Save benmatselby/31728e8cce6b75eb36646c2a7d9ebec8 to your computer and use it in GitHub Desktop.
def decimal_to_roman(num):
"""
Convert a decimal number to Roman numerals.
Args:
num: Integer between 1 and 3999
Returns:
String representing the Roman numeral
"""
if not isinstance(num, int) or num < 1 or num > 3999:
raise ValueError("Number must be an integer between 1 and 3999")
# Mapping of values to Roman numerals in descending order
values = [
(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, numeral in values:
count = num // value
if count:
result += numeral * count
num -= value * count
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment