Skip to content

Instantly share code, notes, and snippets.

@samkahchiin
Created March 27, 2016 09:14
Show Gist options
  • Save samkahchiin/c091e14f5766b5ddc91d to your computer and use it in GitHub Desktop.
Save samkahchiin/c091e14f5766b5ddc91d to your computer and use it in GitHub Desktop.
Convert the given number into a roman numeral.
function convert(num) {
var roman_hash = { "M" : 1000,
"CM" : 900,
"D" : 500,
"CD" : 400,
"C" : 100,
"XC" : 90,
"L" : 50,
"XL" : 40,
"X" : 10,
"IX" : 9,
"V" : 5,
"IV" : 4,
"I" : 1 };
var roman = "";
var keys = Object.keys(roman_hash);
while( num !== 0){
for(var i = 0; i < keys.length; i++){
if( num / roman_hash[keys[i]] >= 1){
for(var j = 0; j < Math.floor( num / roman_hash[keys[i]] ); j++){
roman += keys[i];
}
num = num % roman_hash[keys[i]];
}
}
}
return roman;
}
convert(29);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment