Created
July 23, 2015 09:04
-
-
Save geibi/ca95774caf63cd38e83d to your computer and use it in GitHub Desktop.
Bonfire: Roman Numeral Converter - freecodecamp
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 convert(num) { | |
var arRomans = [ | |
["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], //1 | |
["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], //10 | |
["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] //100 | |
]; | |
var arConverted = []; | |
var strConverted = ""; | |
//reverse given string and make an array from it | |
//365 => Array(5,6,3) | |
//to get decimals in right order => 1,10,100 | |
var arNum = num.toString().split("").reverse(); | |
//loop through digits | |
//5,6,3 = 3 digits | |
for(i=0;i<arNum.length;i++){ | |
//push romans to array | |
//i=0 decimal 1 | |
//i=1 decimal 10 | |
//i=2 decimal 100 | |
//e.g. | |
//5 = arRomans[0][5-1] = arRomans[0][4] = "V" | |
//6 = arRomans[1][6-1] = arRomans[1][5] = "LX" | |
//3 = arRomans[2][3-1] = arRomans[2][2] = "CCC" | |
arConverted.push(arRomans[i][arNum[i]-1]); | |
} | |
//reverse the array again to get it in right order | |
//and convert it to a string to be returned | |
strConverted = arConverted.reverse().join(""); | |
//console.log(strConverted); | |
return strConverted; | |
} | |
convert(999); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment