Skip to content

Instantly share code, notes, and snippets.

@ssomnoremac
Last active August 22, 2016 12:25
Show Gist options
  • Save ssomnoremac/64656bcf7dc4ee70f6bb917a697b02a5 to your computer and use it in GitHub Desktop.
Save ssomnoremac/64656bcf7dc4ee70f6bb917a697b02a5 to your computer and use it in GitHub Desktop.
Convert numbers to Roman numerals
var ROM = [
{key:"M",value:1000},
{key:"D",value:500},
{key:"C",value:100},
{key:"L",value:50},
{key:"X", value:10},
{key:"V",value:5},
{key:"I",value:1}
]
function roman(num){
var remains = num;
var ans = ""
while(remains >= 1000){
remains -= 1000;
ans = ans + "M";
}
for (i = 1; i < ROM.length; i++) {
var part = "";
while(remains >= ROM[i].value){
remains -= ROM[i].value
part = part + ROM[i].key
// 4
if (part.length === 4){
part = ROM[i].key + ROM[i-1].key
}
// 9
if(i%2 ==1){
var check = remains - ROM[i].value + ROM[i+1].value
if (check >= 0){
part = ROM[i+1].key + ROM[i-1].key
remains = check
}
}
}
ans = ans + part
}
return ans
}
@psycalc
Copy link

psycalc commented Aug 22, 2016

function convertToRoman(num) {
if (num === 0) return "";
var associativeArray = {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};
for (var i in associativeArray) {
if (num >= associativeArray[i]) `
num = i + convertToRoman(num - associativeArray[i]);
return num;
}
}
}
console.log("Roman:",convertToRoman(68));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment