Skip to content

Instantly share code, notes, and snippets.

@obritoluis
Created March 14, 2020 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obritoluis/ced0aa098600c1d2a0bca5127f3af2a5 to your computer and use it in GitHub Desktop.
Save obritoluis/ced0aa098600c1d2a0bca5127f3af2a5 to your computer and use it in GitHub Desktop.
freeCodeCamp: Roman Numeral Converter
function convertToRoman(num) {
// define roman numbers combinations
const romanCombinations = {
1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX",
10: "X", 20: "XX", 30: "XXX", 40: "XL", 50: "L", 60: "LX", 70: "LXX", 80: "LXXX", 90: "XC",
100: "C", 200: "CC", 300: "CCC", 400: "CD", 500: "D", 600: "DC", 700: "DCC", 800: "DCCC", 900: "CM",
1000: "M"
}
if (num in romanCombinations) { // check if num is one of the combinations
return romanCombinations[num];
} else {
const numLen = num.toString().length; // get num length
let romanNumerals = ""; // variable to concatenate roman number combinations
let sum = num; // variable that will be used on a while
let i = 0; // var to help on getting the roman number combinations
let romanNum; // number to help accessing a roman number combination
while (sum > 0) { // while the sum=num is bigger than zero
if (sum < 2000) { // check if < 2000, if not we'll have to multiply M
// filter all combinations that have the same length as the [i]th (eg: 150 has a length of 3, so it will check all combinations with 3 digits (100, 200, 300, etc))
// e.g. x.lenght == 3 && x[0] == 4, means a number that starts with 4 with a 3 digits existent on romanCombinations, which means 400
romanNum = Object.keys(romanCombinations).filter(x => x.length == (numLen - i) && x[0] == num.toString()[i]);
if (romanNum.length > 0) { // only if not zero, if zero it skips
romanNumerals = romanNumerals.concat(romanCombinations[romanNum]);
}
} else { // if 2000 or higher, get the right quantity of Ms
romanNum = Math.floor(sum / 1000) * 1000;
romanNumerals = romanNumerals.concat(romanCombinations[1000].repeat(Math.floor(sum / 1000)));
}
sum -= romanNum; // e.g. 4543 -> 543 -> 43 -> 3 -> 0
i++;
}
return romanNumerals;
}
}
convertToRoman(915);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment