大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

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.
Input: num = 3
Output: "III"
Input: num = 4
Output: "IV"
Input: num = 9
Output: "IX"
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
1 <= num <= 3999
首先先簡單的翻譯一下題目
給你十進位的數字轉成羅馬數字表示,然後I可以放在V跟X的前面,X可以放在L跟C的前面,而C可以放在D跟M的前面。
像是:IV,V代表的是5,I代表的是1,IV則代表的是4 (5-1),以此類推。
作法大致上是這樣
IV、IX、XL、XC、CD、CM在計算上有點麻煩,所以我就乾脆把他們一起建在dictionary中。keys()是為了要抓到dictionary中最大的數,用來除讀進來的十進位數,再用商來判斷拿來除的羅馬數字應該要有幾個,餘數再拿來除下一輪的dictionary的數。class Solution:
def intToRoman(self, num: int) -> str:
Symbol_dict = {1:'I', 4: 'IV', 5:'V', 9:'IX', 10:'X',
40:'XL', 50:'L', 90:'XC', 100:'C',
400:'CD', 500:'D', 900:'CM', 1000:'M'}
roman = ""
index = -1
keys = list(Symbol_dict.keys())
while num != 0:
if num // keys[index] == 0:
if num % keys[index] == 0:
roman = Symbol_dict[keys[index]]
return roman
else:
num %= keys[index]
index -= 1
else:
for times in range(num//keys[index]):
roman += Symbol_dict[keys[index]]
num %= keys[index]
index -= 1
return roman
Python
大家明天見![]()