Created
February 10, 2021 20:30
-
-
Save rajivnarayana/0393824935132abef731103c817aaf9f to your computer and use it in GitHub Desktop.
A Javascript program to convert a given number to its roman numeral representation
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
/** | |
* Write a program to encode a given number in roman numeral form | |
// I - 1 | |
// V - 5 | |
// X - 10 | |
// L - 50 | |
// C - 100 | |
// D - 500 | |
// M - 1000 | |
* @param {*} number | |
* function encode(number) { | |
* return "XV"; | |
* } | |
*/ | |
function encode(number) { | |
let exponent = 0; | |
let roman = ""; | |
while(number > 0) { | |
let digit = number % 10; | |
// console.log(encodeDigit(digit, exponent)); | |
roman = encodeDigit(digit, exponent)+roman; | |
number = Math.floor(number / 10); | |
exponent++; | |
} | |
// console.log(`The roman form of ${number} is ${roman}`); | |
return roman; | |
} | |
const numerals = [ | |
{min: 'I', mid: 'V'}, | |
{min: 'X', mid: 'L'}, | |
{min: 'C', mid: 'D'}, | |
{min: 'M', mid: 'N'}, | |
]; | |
function encodeDigit(number, exponent) { | |
const min = numerals[exponent].min; | |
const mid = numerals[exponent].mid; | |
switch(number) { | |
case 0: | |
return ""; | |
case 1: | |
return min; | |
case 2: | |
return `${min}${min}`; | |
case 3: | |
return `${min}${min}${min}`; | |
case 4: | |
return `${min}${mid}`; | |
case 5: | |
return mid; | |
case 6: | |
return `${mid}${min}`; | |
case 7: | |
return `${mid}${min}${min}`; | |
case 8: | |
return `${mid}${min}${min}${min}`; | |
case 9: | |
return `${min}${numerals[exponent+1].min}`; | |
} | |
} | |
function assert(expected, number) { | |
const actual = encode(number); | |
if (expected === actual) { | |
console.log(`Passed ${number} === ${expected}`); | |
return; | |
} | |
console.trace(`Expected ${expected} for ${number} but is actually ${actual}`); | |
} | |
function main() { | |
assert("CCXLVII", 247); | |
assert("CCXCVIII", 298); | |
assert("M", 1000); | |
assert("CM", 900); | |
assert("LV", 55); | |
assert("MMMCMXCIX", 3999); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment