Python Readable 109ms Soln


  • 0

    Basically, take apart the number by increments of a digit.
    Handle the two special cases where 4th and 9th elements are funny.
    Otherwise, the rest is pretty straightforward.

    INT_VALUES = [1,5,10,50,100,500,1000,5000]
    
    INT_ROMAN_NUMERAL = {
        5000: "", # Dummy value
        1000: "M",
        500: "D",
        100: "C",
        50: "L",
        10: "X",
        5: "V",
        1: "I"
    }
    
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            roman_numeral = ""
            int_index = len(INT_VALUES) - 2  # start at index for 1000
            while num > 0:
                int_value = INT_VALUES[int_index]
                division = num/int_value  # 1234567890 can be any of these
                if division == 0:
                    pass
                elif division == 9:  # special case 1
                    roman_numeral += INT_ROMAN_NUMERAL[int_value] + INT_ROMAN_NUMERAL[INT_VALUES[int_index + 2]] # IX
                elif division == 4:  # special case 2
                    roman_numeral += INT_ROMAN_NUMERAL[int_value] + INT_ROMAN_NUMERAL[INT_VALUES[int_index + 1]]
                else:
                    division5 = num/INT_VALUES[int_index + 1]
                    roman_numeral += INT_ROMAN_NUMERAL[INT_VALUES[int_index + 1]] * division5
                    division -= division5 * 5
                    roman_numeral += INT_ROMAN_NUMERAL[int_value] * division
                num = num % int_value
                int_index -= 2
            
            return roman_numeral
    

Log in to reply
 

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