Python2 simple solution by Joey 簡單解


  • 0
    T

    just think of a transistion of decimal to roman,
    using minus value to add a string at one time.
    就想成十進位轉羅馬字的轉換過程,一次減掉一個level的數字來補上一個羅馬文字。

    if num>3999 or num<1:                                                         #for 1~3999 guarentee
                return ''
            decimal = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
            roman = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']   #check by internet 
            ans = ''                                                              #initial
            for i in range(len(decimal)):                                         #main
                while num >= decimal[i]:
                    num -= decimal[i]
                    ans += roman[i]
            return ans
    

Log in to reply
 

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