Create number to Roman mapping lists [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] to ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'].
Recursively call the algorithm to convert the remainder of the input number (after subtracting the closest match multiplied by the number of repeats).
ns = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
rs = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
def convert(n):
for i in range(len(ns)):
idx = ns.index(n) if n in ns else -1
if idx >= 0:
return rs[idx]
if ns[i] < n:
repeat = n // ns[i]
return rs[i] * repeat + convert(n % ns[i])
n = 3876
print(convert(n))
const ns = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const rs = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
function convert(n) {
for (let i = 0; i < ns.length; i++) {
let idx = ns.indexOf(n);
if (idx >= 0) {
return rs[idx];
}
if (ns[i] < n) {
return rs[i].repeat(Math.floor(n / ns[i])) + convert(n % ns[i]);
}
}
}
const n = 3876;
console.log(convert(n));