12. Integer to Roman

Given an integer from 1 to 3999, convert it to a Roman numeral.

Example:

3749 => MMMDCCXLIX

58 => LVIII

1994 => MCMXCIV


Solution

function decimalToRoman(num: number, one: string, five: string, ten: string) {
if (num === 9) return one + ten;
if (num > 5) return five + decimalToRoman(num - 5, one, five, ten);
if (num === 5) return five;
if (num === 4) return one + five;
return one.repeat(num);
}

function intToRoman(num: number): string {
let roman = '';

const thousands = Math.floor(num / 1000);
roman = new Array(thousands).fill('M').join('');

const hundreds = Math.floor(num / 100) % 10;
roman += decimalToRoman(hundreds, 'C', 'D', 'M');

const tens = Math.floor(num / 10) % 10;
roman += decimalToRoman(tens, 'X', 'L', 'C');

const ones = num % 10;
roman += decimalToRoman(ones, 'I', 'V', 'X');

return roman;
}