1. 问题描述
给定一个整数,将其转换为罗马数字,要求返回结果的取值范围为1~3999。
2. 问题示例
4→Ⅳ,12→Ⅻ,21→XⅪ,99→XCIX。
3. 代码实现
def int_to_roman(num):val = [1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1]syb = ["M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V", "IV","I"]roman_num = ''i = 0while num > 0:for _ in range(num // val[i]):roman_num += syb[i]num -= val[i]i += 1return roman_num
print(int_to_roman(4)) # 输出 IV
print(int_to_roman(12)) # 输出 XII
print(int_to_roman(21)) # 输出 XXI
print(int_to_roman(99)) # 输出 XCIX
def int_to_roman(num):roman_dict = {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'}roman_num = ''for value, symbol in roman_dict.items():while num >= value:roman_num += symbolnum -= valuereturn roman_num
print(int_to_roman(4)) # 输出 IV
print(int_to_roman(12)) # 输出 XII
print(int_to_roman(21)) # 输出 XXI
print(int_to_roman(99)) # 输出 XCIX