Last active
August 22, 2016 12:25
-
-
Save ssomnoremac/64656bcf7dc4ee70f6bb917a697b02a5 to your computer and use it in GitHub Desktop.
Convert numbers to Roman numerals
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
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
commented
Aug 22, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment