Posted on 2022-11-03 01:46
Uriel 閱讀(72)
評論(0) 編輯 收藏 引用 所屬分類:
字符串處理 、
閑來無事重切Leet Code
阿拉伯數字轉羅馬字符,簡單字符串處理,用了python的dict
1 #12
2 #Runtime: 59 ms
3 #Memory Usage: 13.2 MB
4
5 class Solution(object):
6 def intToRoman(self, num):
7 """
8 :type num: int
9 :rtype: str
10 """
11 dict = {1 : 'I', 5 : 'V', 10 : 'X', 50 : 'L', 100 : 'C', 500 : 'D', 1000 : 'M'}
12 nt = 1
13 ans = []
14 while num > 0:
15 tp = num % 10
16 if tp == 4:
17 ans.append(dict[nt] + dict[5*nt])
18 elif tp == 9:
19 ans.append(dict[nt] + dict[10*nt])
20 elif tp < 4 and tp > 0:
21 ans.append(dict[nt] * tp)
22 elif tp >= 5:
23 ans.append(dict[5*nt] + dict[nt] * (tp - 5))
24 num = num // 10
25 nt = nt * 10
26 ans.reverse()
27 return ''.join(ans)