Last active
December 12, 2015 08:19
-
-
Save scizo/4743602 to your computer and use it in GitHub Desktop.
Roman Numeral Exercise
This file contains hidden or 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 romanNumeral(n) { | |
var result = '', | |
thousands = integerDivision(n,1000), | |
hundreds = integerDivision((n % 1000),100), | |
tens = integerDivision((n % 100),10), | |
ones = n % 10; | |
result += stringTimes(thousands,'m'); | |
result += romanHelper(hundreds,'c','d','m'); | |
result += romanHelper(tens,'x','l','c'); | |
result += romanHelper(ones,'i','v','x'); | |
return result; | |
} | |
function romanHelper(n, oneChar, fiveChar, tenChar) { | |
var fives = integerDivision(n,5), | |
ones = n % 5; | |
if (ones == 4) { | |
if (fives) | |
return oneChar + tenChar; | |
else | |
return oneChar + fiveChar; | |
} else { | |
return stringTimes(fives,fiveChar) + stringTimes(ones,oneChar); | |
} | |
} | |
function integerDivision(a,b) { | |
return Math.floor(a/b); | |
} | |
function stringTimes(n,char) { | |
var str = ""; | |
for(var i = 0; i < n; i++) { | |
str += char; | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment