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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(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:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Related Topics: Math
、String
解題邏輯與實作
厄… 解法有點偷懶,我直接 hard code 一張對照表,把所有可能的組合列出,在依序找出數字中包含的最大的可轉化為羅馬數字的數字。例如 1994,最大可轉換數字是 1000 ,減去 1000 後接下來依序可轉換數字為 900 、90、4,因此最後輸出 MCMXCIV。
1 |
|
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 ,可在細分成
- 100 ~ 300: C*n ,這區間直接以 100 的羅馬符號 C 表示,最高位則是羅馬符號的出現次數。
- 400: CD , 對照回 array 可表示成 array[index] + array[index-1] 。
- 500 :D , array[index-1] 。
- 600 ~ 800 : DC*n ,表示成 500 + 100 ~300。
- 900 :CM ,對照回 array 可表示成 array[index] + array[index-2] 。 基本上個、十、百位數的情況都類似,而千位數因題限制輸入範圍只到 3999,所以只會出現 case 1。
1 |
|