LeetCode--Integer to Roman

来源:互联网 发布:java开发项目案例 编辑:程序博客网 时间:2024/06/08 11:26

题目:

将数字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

原创粉丝点击