Simple python code


  • 1
    H
    class Solution:
    # @return a string
    def intToRoman(self, num):
        roman_char = {
            1 : 'I',
            5 : 'V',
            10 : 'X',
            50 : 'L',
            100 : 'C',
            500 : 'D',
            1000 : 'M'
            }
        n = 1000
        ret = ''
        while num > 0:
            d = num / n
            if d > 0 and d < 4:
                for i in range(0,d):
                    ret += roman_char[n]
            elif d == 0:
                pass
            elif d == 4:
                ret += roman_char[n] + roman_char[5*n]
            elif d == 5:
                ret += roman_char[5*n]
            elif d > 5 and d < 9:
                ret += roman_char[5*n]
                for i in range(1,d-4):
                    ret +=  roman_char[n]
            elif d == 9:
                ret += roman_char[n] + roman_char[10*n]
    
            num -= d*n
            n/= 10
    
        return ret
    

    runtime:126ms


  • 0
    T

    I have exactly same idea.


Log in to reply
 

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