12. 整数转罗马数字

罗马数字包含以下七种字符: I, V, X, LCD 和 M

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

  • I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
  • X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
  • C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。

给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。

示例 1:

输入: 3
输出: "III"

示例 2:

输入: 4
输出: "IV"

示例 3:

输入: 9
输出: "IX"

示例 4:

输入: 58
输出: "LVIII"
解释: L = 50, V = 5, III = 3.

示例 5:

输入: 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.

提示:

  • 1 <= num <= 3999

recursive

class Solution:
    def intToRoman(self, num: int) -> str:
        dict = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
        special=[4,9,40,90,400,900]
        special_dict={4:'IV',9:'IX',40:'XL',90:'XC',400:'CD',900:'CM'}
        
        if num==0:
            return ''
        if str(num)[0]=='4':
            base=400
            while num-base<0:
                base//=10
            # Recursive 
            return special_dict[base]+self.intToRoman(num-base)
        if str(num)[0]=='9':
            base=900
            while num-base<0:
                base//=10
            # Recursive 
            return special_dict[base]+self.intToRoman(num-base)

        #see if num>500 or num>1000
        keys = sorted(list(dict.keys()),reverse=True)
        for base in keys:
            if num//base>0:
                i = num//base
                # Recursive 
                return dict[base]*i+self.intToRoman(num%base)

taxonom 

class Solution:
    def intToRoman(self, num: int) -> str:
        roman =['M','D','C','L','X','V','I']
        nums =[1000,500,100,50,10,5,1]
        res =''
        # divided into 1-3 4 5 6-8 9
        for i in range(0,len(nums),2):
            x = num//nums[i]
            if x<4:
                res+=(roman[i]*x)
            if x==4:
                res+=roman[i]+roman[i-1]
            if x==5:
                res+=roman[i-1]
            if x>5 and x<9:
                # more than 5 parts
                res+=(roman[i-1]+roman[i]*(x-5))
            if x==9:
                res+=roman[i]+roman[i-2]
            num%=nums[i]
        return res
原文地址:https://www.cnblogs.com/xxxsans/p/14768184.html