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, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven 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 is guaranteed to be within the range from 1 to 3999.

Example 1:

 12 Input: 3 Output: "III" 

Example 2:

 12 Input: 4 Output: "IV" 

Example 3:

 12 Input: 9 Output: "IX" 

Example 4:

 123 Input: 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3. 

Example 5:

 123 Input: 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 

Related Topics: MathString

## 解題邏輯與實作

 1234567891011121314 class Solution: def intToRoman(self, num: int) -> str: int_to_roman = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')) result = "" for k_int, v_roman in int_to_roman: digital = num // k_int if digital > 0 : result += (v_roman * digital) num %= k_int return result 

P.S. 這應該算是貪婪演算法！？

array

int 1000 500 100 50 10 5 1
roman M D C L X V I
index 0 1 2 3 4 5 6

1. 100 ~ 300： C*n ，這區間直接以 100 的羅馬符號 C 表示，最高位則是羅馬符號的出現次數。
2. 400： CD ， 對照回 array 可表示成 array[index] + array[index-1] 。
3. 500 ：D ， array[index-1] 。
4. 600 ~ 800 ： DC*n ，表示成 500 + 100 ~300。
5. 900 ：CM ，對照回 array 可表示成 array[index] + array[index-2] 。 基本上個、十、百位數的情況都類似，而千位數因題限制輸入範圍只到 3999，所以只會出現 case 1。
 1234567891011121314151617181920212223 class Solution: def intToRoman(self, num: int) -> str: int_to_roman = ((1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I')) result = "" for i in range(0, len(int_to_roman), 2): k_int, v_roman = int_to_roman[i] digital = num // k_int if(1 <= digital <= 3): result += (v_roman * digital) elif(digital == 4): result += v_roman + int_to_roman[i-1][1] elif(5 <= digital <= 8): result += int_to_roman[i-1][1] + v_roman * (digital - 5) elif(digital == 9): result += v_roman + int_to_roman[i-2][1] num %= k_int return result