From 82e9839d6b5afbc2c4bdd4983e17c5c78bf1ccf2 Mon Sep 17 00:00:00 2001 From: CherryKitten Date: Thu, 13 Oct 2022 20:05:33 +0200 Subject: [PATCH] Add roman numeral converter certification project --- .../2-roman-numerals.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 2-javascript-algorithms-datastructures/2-roman-numerals.js diff --git a/2-javascript-algorithms-datastructures/2-roman-numerals.js b/2-javascript-algorithms-datastructures/2-roman-numerals.js new file mode 100644 index 0000000..c75f02d --- /dev/null +++ b/2-javascript-algorithms-datastructures/2-roman-numerals.js @@ -0,0 +1,17 @@ +const romanNumerals = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] +const arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] +function convertToRoman(num) { + const converted = []; + for (let item in arabicNumerals){ + while (num >= arabicNumerals[item]){ + converted.push(romanNumerals[item]); + num = num - arabicNumerals[item]; + } + } + return converted.join("") +} + +let test1 = convertToRoman(36); //XXXVI +let test2 = convertToRoman(2014);//MMXIV +let test3 = convertToRoman(9);//IX +let test4 = convertToRoman(3999);//MMMCMXCIX \ No newline at end of file