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.Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Related Topics: Math
、String
厄… 解法有點偷懶,我直接 hard code 一張對照表,把所有可能的組合列出,在依序找出數字中包含的最大的可轉化為羅馬數字的數字。例如 1994,最大可轉換數字是 1000 ,減去 1000 後接下來依序可轉換數字為 900 、90、4,因此最後輸出 MCMXCIV。
P.S. 這應該算是貪婪演算法!?
不過這個版本直接把 4 這個特殊情況都直接 hard code 進去。所以後來又試著做只使用標準符號的。
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 |
觀察一下,以百位數區間為例(index == 2),除了本身有符號表示的 500 與 100 ,可在細分成
本文作者: 辛西亞.Cynthia
本文連結: 辛西亞的技能樹 / hackmd 版本
版權聲明: 部落格中所有文章,均採用 姓名標示-非商業性-相同方式分享 4.0 國際 (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!