A more general solution


  • 0
    V
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
    
            conv = 'IVXLCDM'
            i = 3
            ans = []
            while i >= 0:
                div = num // 10**i
                num = num % 10**i
    
                if div > 0:
                    if div <= 3:
                        ans += [conv[2 * i]] * div
                    elif div == 4:
                        ans += [conv[2 * i]] + [conv[2 * i + 1]]
                    elif div <= 8:
                        ans += [conv[2 * i + 1]] + [conv[2 * i]] * (div - 5)
                    else:
                        ans += [conv[2 * i]] + [conv[2 * i + 2]]
                i -= 1
                    
            return ''.join(ans)
    

    If a larger range of numbers is to be converted, only the initial values of i and conv have to be updated.


Log in to reply
 

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