Skip to content

Instantly share code, notes, and snippets.

@ujjawalsidhpura
Created September 4, 2021 22:20
Show Gist options
  • Select an option

  • Save ujjawalsidhpura/4b6c85ef9a412b774bd0c6a636a7e7a7 to your computer and use it in GitHub Desktop.

Select an option

Save ujjawalsidhpura/4b6c85ef9a412b774bd0c6a636a7e7a7 to your computer and use it in GitHub Desktop.
Basic Roman Numerals
Have the function BasicRomanNumerals(str) read str which will be a string of Roman numerals.
The numerals being used are: I for 1, V for 5, X for 10, L for 50, C for 100, D for 500 and M for 1000.
In Roman numerals, to create a number like 11 you simply add a 1 after the 10, so you get XI.
But to create a number like 19, you use the subtraction notation which is to add an I before an X or V
(or add an X before an L or C). So 19 in Roman numerals is XIX.
The goal of your program is to return the decimal equivalent of the Roman numeral given.
For example: if str is "XXIV" your program should return 24
function BasicRomanNumerals(str) {
let arr = []
str.split('').forEach(num => {
switch (num) {
case 'I':
arr.push(1);
break;
case 'V':
arr.push(5);
break;
case 'X':
arr.push(10);
break;
case 'L':
arr.push(50);
break;
case 'C':
arr.push(100);
break;
case 'D':
arr.push(500);
break;
case 'M':
arr.push(1000);
break;
}
});
let res = 0;
let x;
let y;
//For Even Roman digits
if (arr.length % 2 === 0) {
for (let i = 0, j = 1; i < arr.length; i += 2, j += 2) {
x = arr[i];
y = arr[j];
if (arr[i] < arr[j]) {
res += (y - x)
} else {
res += (y + x)
}
}
} // For Odd Roman digits
else {
// Case 1: when first two digits are ascending
if (arr[0] > arr[1]) {
res += arr[0];
arr.shift();
for (let i = 0, j = 1; i < arr.length; i += 2, j += 2) {
x = arr[i];
y = arr[j];
if (arr[i] < arr[j]) {
res += (y - x)
} else {
res += (y + x)
}
}
} else {
// Case 2: when first two digits are descending
res += arr[arr.length - 1];
arr.pop();
for (let i = 0, j = 1; i < arr.length; i += 2, j += 2) {
x = arr[i];
y = arr[j];
if (arr[i] < arr[j]) {
res += (y - x)
} else {
res += (y + x)
}
}
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment