I've done an iterative solution in Python


  • 0
    D
    class Solution(object):
           
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            def buildNum(n,one,five,ten):
                rnum=""
                if(n<4):
                    rnum=one * n
                else:
                    if(n>5 and n<9):
                        rnum=five+one*(n-5)
                    else:
                        if(n==4 or n==5):
                            rnum=one*(5-n)+five
                        else:
                            if(n==9):
                                rnum=one+ten
                return rnum
            
            conv_dict={1: 'I', 5: 'V', 10: 'X', 50: 'L',
                      100: 'C', 500: 'D', 1000: 'M', 5000: ' ', 10000: ' '}
            roman=""
            one=1
            five=5
            ten=10
            while(num>0):
                #extract last digit
                digit=num %10
                #add roman digits
                roman=buildNum(digit,conv_dict[one],conv_dict[five],conv_dict[ten])+roman
                #prepare for next pass
                num=num//10
                one=one*10
                five=five*10
                ten=ten*10
            return roman
    

Log in to reply
 

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