Skip to content

Instantly share code, notes, and snippets.

@scizo
Last active December 12, 2015 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scizo/4743602 to your computer and use it in GitHub Desktop.
Save scizo/4743602 to your computer and use it in GitHub Desktop.
Roman Numeral Exercise
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