Simple python code


  • 0
    J
    def helper(res, first, fifth, tenth, num):
        if num <= 3:
            return res + num*first
        elif num == 4:
            return res + first + fifth
        elif num == 5:
            return res + fifth
        elif num <= 8:
            return res + fifth + (num-5)*first
        elif num == 9:
            return res + first + tenth
    
    class Solution:
        # @return a string
        def intToRoman(self, num):
        	# I V X
            # X L C
            # C D M
            res = ''
            res = helper(res,'M','L','L', num // 1000 )
            num = num % 1000
            res = helper(res,'C','D','M', num // 100 )
            num = num % 100
            res = helper(res,'X','L','C', num // 10 )
            num = num % 10
            res = helper(res,'I','V','X', num)
            return res
    

    120 ms

    observe pattern and make up the string


  • 0
    M

    I have a very similar solution! I like your "helper" function!

    class Solution:
    # @return a string
    def intToRoman(self, num):
        s=[int(x) for x in list(str(num))]
        rom=''
        for i,num in enumerate(reversed(s)):
            if i==0:
                L1='I'
                L5='V'
                L10='X'
            if i==1:
                L1='X'
                L5='L'
                L10='C'
            if i==2:
                L1='C'
                L5='D'
                L10='M'
            if i==3:
                L1='M'
                
            if num==1:
                rom=L1+rom
            if num==2:
                rom=L1+L1+rom
            if num==3:
                rom=L1+L1+L1+rom
            if num==4:
                rom=L1+L5+rom
            if num==5:
                rom=L5+rom
            if num==6:
                rom=L5+L1+rom
            if num==7:
                rom=L5+L1+L1+rom
            if num==8:
                rom=L5+L1+L1+L1+rom
            if num==9:
                rom=L1+L10+rom
                
        return rom

Log in to reply
 

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