Skip to content

Instantly share code, notes, and snippets.

@uttamk
Last active September 29, 2021 11:16
Show Gist options
  • Save uttamk/d6dd75cf930f2287ac8ded1ba8020cc4 to your computer and use it in GitHub Desktop.
Save uttamk/d6dd75cf930f2287ac8ded1ba8020cc4 to your computer and use it in GitHub Desktop.
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