題目
這題跟 13.Roman to Integer 是同類型題目,只不過這題是將整數轉為羅馬數字。
羅馬數字以七個不同的符號表示:I、V、X、L、C、M 。
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
羅馬數字通常從左到右從最大到最小書寫。不過有六種使用減法的情況:
I在V(5) 和X(10) 之前會組成 4 和 9。X在L(50) 和C(100) 之前會組成 40 和 90。C在D(500) 和M(1000) 之前會組成 400 和 900。
解題思路
- 首先依據羅馬數字每個符號與對應的值建一個 map。 羅馬數字是由大到小書寫,為了處理方便,romanMap 也應該改成由大到小排序。
const romanMap = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
}- 接著從前往後遍歷 romanMap keys
- 檢查
num是否大於等於當前羅馬數字符號的值- 是:將對應的羅馬數字符號加到
result中,並從num中減去該羅馬數字符號的值 - 否:不做任何事
- 是:將對應的羅馬數字符號加到
- 繼續這個過程直到
num小於羅馬數字符號的值,再繼續處理下一個羅馬數字符號
- 檢查
- 返回
result
完整程式碼
/**
* @param {number} num
* @return {string}
*/
const romanMap = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
}
var intToRoman = function(num) {
const keys = Object.keys(romanMap)
let result = ''
for (key of keys) {
const value = romanMap[key]
while (num >= romanMap[key]) {
result += key
num -= romanMap[key]
}
}
return result
};
![[LeetCode] 12. Integer to Roman (JS) 1 [LeetCode] 12. Integer to Roman (JS)](https://www.may-notes.com/wp-content/uploads/2024/06/LeetCode_Sharing.png)
![[LeetCode] 13. Roman to Integer (JS) 2 LeetCode Sharing](https://www.may-notes.com/wp-content/uploads/2024/06/LeetCode_Sharing-150x150.png)
![[React] Redux Toolkit Query(RTKQ) 基礎使用指南 3 RTKQ logo](https://www.may-notes.com/wp-content/uploads/2023/12/nl9bkr5l1h5ke31vkula-150x150.webp)



![[Weekly] 07/08-07/14 本周紀錄 9 weekly-banner](https://www.may-notes.com/wp-content/uploads/2023/10/jazmin-quaynor-18mUXUS8ksI-unsplash-150x150.jpg)