My python solution easy to understand.


  • 0
    R

    Use dictionary and divmod

        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            dic = {"M":1000,"CM":900,"D":500,"CD":400,"C":100,"XC":90,"L":50,"XL":40,"X":10,"IX":9,"V":5,"IV":4,"I":1}
            dic_keys = sorted(dic.keys(), key=dic.get, reverse=True)
            result = ''
            for k in dic_keys:
                quotient, num = divmod(num, dic[k]) # num = remainder 
                if quotient != 0:
                    result += k*quotient
                if num == 0:
                    return result
            return result
    

  • 0
    C

    @rarezhang Just curious how to retrieve the keys from the dic orderly (here 'M', 'CM', --->'I')? dic_keys = sorted(dic.keys(), key=dic.get, reverse=True) works? If so, cool.


Log in to reply
 

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