Created
January 17, 2016 02:36
-
-
Save nickrobson/4ca440b041775395f864 to your computer and use it in GitHub Desktop.
Converts decimal 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
function convert(num) { | |
var map = [ | |
[1, 1, 'I'], | |
[1, 5, 'V'], | |
[2, 10, 'X'], | |
[2, 50, 'L'], | |
[3, 100, 'C'], | |
[3, 500, 'D'], | |
[4, 1000, 'M'], | |
[4, 5000, ''], | |
[5, 10000, ''] | |
]; | |
function get_rom(digit, n) { | |
var unit = map.filter(function(a) { return a[0] == n; })[0][2]; | |
var five = map.filter(function(a) { return a[0] == n; })[1][2]; | |
var ten = map.filter(function(a) { return a[0] == n+1; })[0][2]; | |
var rom = ''; | |
switch (digit) { | |
case 9: return unit+ten; | |
case 8: rom += unit; | |
case 7: rom += unit; | |
case 6: rom += unit; | |
case 5: return five+rom; | |
case 4: return unit+five; | |
case 3: rom += unit; | |
case 2: rom += unit; | |
case 1: rom += unit; | |
case 0: return rom; | |
} | |
return ''; | |
} | |
var dec = '' + num; | |
var str = ''; | |
for (var i = dec.length; i > 0; i--) { | |
str += get_rom(parseInt(dec[dec.length-i]), i); | |
} | |
return str; | |
} | |
convert(123); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment