题目:
将数字num转为罗马数字格式
思路:
先给出所有的罗马数字表示组合,如dict所示dict_integer = {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'}。再使用贪心算法,每次都从上列组合中选出可选择的最大数,将该表示加入输出字符串,再将num减去选中的最大数,直到num变为0结束。
代码(python):
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
dict_integer = {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'}
list_integer = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
output = ''
temp = 0
while(num):
if list_integer[temp]<=num:
output = output+dict_integer[list_integer[temp]]
num = num-list_integer[temp]
else:
temp=temp+1
continue
return output