Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.
For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty-seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Given an integer, convert it to a roman numeral.
def intToRoman(num):
# Define the mapping of values to Roman numeral symbols
val_to_roman = [
(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')
]
# Initialize the result string
roman_numeral = ""
# Convert the number to a Roman numeral
for val, roman in val_to_roman:
while num >= val:
roman_numeral += roman
num -= val
return roman_numeral
# Example usage
print(intToRoman(1994)) # Output: 'MCMXCIV'
This solution is efficient and scales appropriately within the given constraints of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?