My Different O(len_chars) Solution


  • 0
    F
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            roman_int_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
            roman_chars = 'MDCLXVI'
            s = ''
            for i in range(len(roman_chars) - 1):
                d = num // roman_int_dict[roman_chars[i]]
                d_sub = (num - d * roman_int_dict[roman_chars[i]]) // roman_int_dict[roman_chars[i + 1]]
                if d_sub == 4:
                    num = num + roman_int_dict[roman_chars[i + 1]] - roman_int_dict[roman_chars[i - d]]
                    s = s + roman_chars[i + 1] + roman_chars[i - d]
                else:
                    num = num - roman_int_dict[roman_chars[i]] * d
                    s = s + roman_chars[i] * d
            return s + 'I' * num
                    
    

Log in to reply
 

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