1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| function convertToRoman(num) { let obj = { I: 1, II: 2, III: 3, IV: 4, V: 5, VI: 6, VII: 7, VIII: 8, IX: 9, X: 10, L: 50, C: 100, D: 500, M: 1000 } let s = ["I", "V", "X", "L", "C", "D", "M"]
let values = Object.values(obj) let keys = Object.keys(obj)
let arr = String(num).split("").reverse().map(item => Number(item))
for (let i = 0, n =0; i < arr.length; i++, n+=2) { if(arr[i]!==0){ arr[i] = keys[values.indexOf(arr[i])].split("")
for(let j = 0; j < arr[i].length; j++) { arr[i][j]=s[s.indexOf(arr[i][j])+n] }
arr[i] = arr[i].join("")
} else{ arr[i]==="0" } } return arr.reverse().join("").replace(/0/g,"")
}
console.log(convertToRoman(500));
|