Last active
August 29, 2015 14:16
-
-
Save stayradiated/347e3c2bf0037453028c 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 MIN = 1; | |
var MAX = 3999; | |
var CHARS = 'IVXLCDM '; | |
function toRomanNumeral (input) { | |
if (input > MAX || input < MIN) { | |
throw new Error('Cannot convert number'); | |
} | |
var offset = CHARS.length - 3; | |
var digit = 0; | |
var multiplyer = 1000; | |
var roman = ''; | |
while (multiplyer >= 1) { | |
digit = Math.floor(input / multiplyer); | |
roman += itor(digit, CHARS[offset], CHARS[offset+1], CHARS[offset+2]); | |
input -= (digit * multiplyer); | |
multiplyer /= 10; | |
offset -= 2; | |
} | |
return roman; | |
} | |
function itor (n, I, V, X) { | |
if (n == 0) return ''; | |
if (n == 1) return I; | |
if (n == 2) return I+I; | |
if (n == 3) return I+I+I; | |
if (n == 4) return I+V; | |
if (n == 5) return V; | |
if (n == 6) return V+I; | |
if (n == 7) return V+I+I; | |
if (n == 8) return V+I+I+I; | |
if (n == 9) return I+X; | |
if (n == 10) return X; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment