iT邦幫忙

0

leetcode with python:12. Integer to Roman

  • 分享至 

  • xImage
  •  

題目:

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol:Value
I:1
V:5
X:10
L:50
C:100
D:500
M:1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.

題目給我們Roman numeral的規定,再給我們數字求出其Roman numeral表示字串

這題像是13.的延伸題

class Solution:
    def intToRoman(self, num: int) -> str:
        d={"1":"I","5":"V","10":"X","50":"L","100":"C","500":"D","1000":"M","4":"IV","9":"IX","40":"XL","90":"XC","400":"CD","900":"CM"} #紀錄轉換規則的dictionary
        
        num=str(num)[::-1] #數字轉字串反轉,方便操作
        ans=""
        
        x=""
        for i in num:
            biggerthanfive=False
            if i in "49": #小心4,9特例
                ans=d[i+x]+ans
            else:
                i=int(i)
                if i>=5:
                    i=i-5
                    biggerthanfive=True
                    
                if i:
                    ans=d["1"+x]*i+ans
                    
                if biggerthanfive:
                    ans=d["5"+x]+ans
                
            x=x+"0" #以0紀錄位數,也方便操作
            
        return ans

建立hash map作為我們轉換的基礎
從個位數開始,我們逐數字的每一位數下去操作,x紀錄現在的位數
特別注意4,9這些特例(hash map有特別對應值)
其餘就按照下列操作
先判斷有沒有大於5,大於該位數就-5並記錄
接著判斷該位有幾個1,搭配x轉換成該數量該位代表1的羅馬文字加入回傳字串
若有紀錄大於五,則字串再加上該位代表5的羅馬文字
逐位操作完後我們就獲得該數字的羅馬文字了
最後執行時間45ms(faster than 97.67%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言