Short'n'Sweet Python solution, beats 90%


  • 2
    d = { 3 :  {1 : "M", 2 : "MM", 3 : "MMM"},
          2 :  {1 : "C", 2 : "CC", 3 : "CCC", 4 : "CD", 5 : "D", 6 : "DC", 7 : "DCC", 8 : "DCCC", 9 : "CM"},
          1 :  {1 : "X", 2 : "XX", 3 : "XXX", 4 : "XL", 5 : "L", 6 : "LX", 7 : "LXX", 8 : "LXXX", 9 : "XC"},
          0 :  {1 : "I", 2 : "II", 3 : "III", 4 : "IV", 5 : "V", 6 : "VI", 7 : "VII", 8 : "VIII", 9 : "IX"}
        }
    
    
    
    class Solution(object):
        def intToRoman(self, num):
            i, res = 0, ""
            while num:
                dig = num % 10
                if dig != 0:
                    s = d[i][dig] + s
                i += 1    
                num /= 10
            return res

  • 0
    W

    Like your method, very clean.
    My version with minor modification:

    dic = {0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX',
            10:'X',20:'XX',30:'XXX',40:'XL',50:'L',60:'LX',70:'LXX',80:'LXXX',90:'XC',
            100:'C',200:'CC',300:'CCC',400:'CD',500:'D',600:'DC',700:'DCC',800:'DCCC',900:'CM',
            1000:'M',2000:'MM',3000:'MMM'
            }
    def intToRoman(self, num):
        return self.dic[num//1000*1000]+self.dic[num%1000//100*100]+self.dic[num%100//10*10]+self.dic[num%10]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.