leetcode-12-integer-to-roman
題目
Seven different symbols represent Roman numerals with the following values:
Symbol | Value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
D | 500 |
M | 1000 |
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.
Given an integer, convert it to a Roman numeral.
Example 1
1 | Input: num = 3749 |
Example 2
1 | Input: num = 58 |
Example 3
1 | Input: num = 1994 |
Constraints:
- 1 <= num <= 3999
解釋題目
是第 13 題的相反過來。給你一個整數(範圍 1~3999),把它轉換成正確的羅馬數字表示法。
組成規則:
- 羅馬數字是由大到小依序組合而成,例如 27 = XXVII(10+10+5+1+1)。
- 但遇到 4 或 9 時,要用「減法」的方式表示,例如 4 = IV(5-1),9 = IX(10-1)。
- 只有 I、X、C、M 這些 10 的倍數可以連續出現最多三次,像 III = 3、XXX = 30。
- 5、50、500(V、L、D)不能連續出現。
遇到 4、9、40、90、400、900 這些數字時,要用減法(IV、IX、XL、XC、CD、CM)。
思路 (1)
- 這題有個重要關鍵,就是組成羅馬數字的所有組合只有13 個,所以可以全部列出來。
- 利用除法是不斷的減去的概念遍歷以上 13 組羅馬數字的組合。
- 由大值到小值依序遍歷,所以 要用陣列組合,才有順序,最後可求出羅馬數字。
程式碼 (1)
1 | class Solution: |