Skip to content

Instantly share code, notes, and snippets.

@uttamk
Last active Sep 29, 2021
Embed
What would you like to do?
var intToRoman = function (num) {
let output = "";
const bases = [1000, 100, 10, 1];
for (let base of bases) {
const q = Math.floor(num / base);
const rem = num % base
if (q > 0) {
output += toFullBaseRoman(q, base);
}
num = rem;
}
return output;
};
function toFullBaseRoman(num, base) {
if (num === 0) {
return "";
}
if (num < 4) {
return repeatChar(baseMap[base], num);
} else if (num === 4) {
return `${baseMap[base]}${baseMap[5 * base]}`
} else if (num === 5) {
return baseMap[num * base];
} else if (num > 5 && num < 9) {
return `${baseMap[5 * base]}${repeatChar(baseMap[base], num - 5)}`
} else {
return `${baseMap[base]}${baseMap[base * 10]}`
}
}
const baseMap = {
1000: "M",
500: "D",
100: "C",
50: "L",
10: "X",
5: "V",
1: "I"
}
function repeatChar(char, times) {
let str = "";
for (let i = 0; i < times; i++) {
str += char;
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment