Last active
August 22, 2023 14:29
-
-
Save nickihastings/df9d751a11bfb7b1e02a4d041e827d8d to your computer and use it in GitHub Desktop.
Convert the given number into a roman numeral. All roman numerals answers should be provided in upper-case.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertToRoman(num) { | |
var singles = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; | |
var tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; | |
var hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; | |
var thousands = ["", "M", "MM", "MMM", "MMMM"]; | |
//turn the number to a string, split individual characters and then turn each one to a number. | |
var length = num.toString().length; | |
var numbers = num.toString().split("").map(Number); | |
var roman = ''; | |
var i = 0; | |
switch (length) { | |
case 4: | |
roman = thousands[numbers[i]]; | |
i++; | |
case 3: | |
roman += hundreds[numbers[i]]; | |
i++; | |
case 2: | |
roman += tens[numbers[i]]; | |
i++; | |
case 1 : | |
roman += singles[numbers[i]]; | |
} | |
return roman; | |
} | |
convertToRoman(36); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment