An Extendable Solution in Python


  • 1
    H

    This solution could be easily extended to larger numbers.

    class Solution:
        # @return a string
        def intToRoman(self, num):
            # I V X L C D M
            dic1 = ['I', 'X', 'C', 'M']
            dic5 = ['V', 'L', 'D']
            d = [0]*4
            i = 0
            while num > 0:
                d[i] = num % 10
                num /= 10
                i += 1
            s = ''
            for j in range(3, -1, -1):
                if d[j] == 9:
                    s += dic1[j] + dic1[j+1]
                elif d[j] == 4:
                    s += dic1[j] + dic5[j]
                else:
                    if d[j] >= 5:
                        s += dic5[j]
                        d[j] -= 5
                    for i in range(0, d[j]):
                        s += dic1[j]
            return s

Log in to reply
 

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