Post your Roman Numeral Converter solutions here!

Hey all!

First off CONGRATULATIONS on being half way through the bootcamp!! :partying_face: :partying_face: :purple_heart:

Let’s post our solutions to the roman numeral converter project here.

I’ll go first!

class NumeralConverter {
  constructor(newValue) {
    this.value = newValue;
    this.numeral = "";
  }

  processNumeral(symbol, symbolValue) {
    while (this.value >= symbolValue) {
      this.numeral += symbol;
      this.value -= symbolValue;
    }
  }
}

function convertToRoman(num) {
  let converter = new NumeralConverter(num);
  converter.processNumeral('M', 1000);
  converter.processNumeral('CM', 900);
  converter.processNumeral('D', 500);
  converter.processNumeral('CD', 400);
  converter.processNumeral('C', 100);
  converter.processNumeral('XC', 90);
  converter.processNumeral('L', 50);
  converter.processNumeral('XL', 40);
  converter.processNumeral('X', 10);
  converter.processNumeral('IX', 9);
  converter.processNumeral('V', 5);
  converter.processNumeral('IV', 4);
  converter.processNumeral('I', 1);
  return converter.numeral;
}
9 Likes

3 Likes

There we go!

const convertPos = (num, base) => {
  const n0=base[0];
  const n1=base[1];
  const n2=base[2];
  switch(num){
    case 0:
      return ""
    case 1:
      return n0
    case 2:
      return n0+n0
    case 3:
      return n0+n0+n0
    case 4:
      return n0+n1
    case 5:
      return n1
    case 6:
      return n1+n0
    case 7:
      return n1+n0+n0
    case 8:
      return n1+n0+n0+n0
    case 9:
      return n0+n2
    default:
      return "\n ERROR (Even though this might never happen)\n"
  }
}

function convertToRoman(num) {
  let ret = ""
  let fNum = num;
  let currDigit;
  const length = num.toString().length;
  
  for(let i=length; i>=0; i--){
    if(i==4){
      currDigit = Math.floor(fNum/1000);
      if (currDigit > 3){
        return "\n ERROR: The thousend's digit should not be larger than 3 \n"
      };
      ret += convertPos(currDigit, ["M","",""]);
      fNum -= 1000*currDigit;
    } 
    else if(i==3){
      currDigit = Math.floor(fNum/100);
      ret += convertPos(currDigit, ["C","D","M"]);
      fNum -= 100*currDigit
    } 
    else if(i==2){
      currDigit = Math.floor(fNum/10);
      ret += convertPos(currDigit, ["X","L","C"]);
      fNum -= 10*currDigit;
    } 
    else if(i==1){
      currDigit = Math.floor(fNum/1);
      ret += convertPos(currDigit, ["I","V","X"]);
      fNum -= 1*currDigit;
    }
  }
 return ret.toUpperCase();
}
//console.log(convertToRoman(parseInt(process.argv[2])));
4 Likes

var roman = {

1:‘I’,

4:‘IV’,

5:‘V’,

9:‘IX’,

10:‘X’,

40:‘XL’,

50:‘L’,

90:‘XC’,

100:‘C’,

400:‘CD’,

500:‘D’,

900:‘CM’,

1000:‘M’

}

function convertToRoman(num) {

let result=’’

let i=Object.keys(roman).length-1

let key

while (i>=0){

key=Object.keys(roman)[i];

while(num>key-1){

 result +=roman[key]

 num -=key;

}



 i -=1;

}

return result;

}

1 Like

Here is mine!

function convertToRoman(num) 
{
  const romanNumeral = 
  {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000,
  }

  let findRomanNumeralDigit = (num) => {
    const keys = Object.keys(romanNumeral)
    for (var i = 0; i < keys.length; i++) {
      if (num - romanNumeral[keys[i]] < 0) {
        return (keys[i-1]);
      }
    }
    return keys[keys.length-1];
  }

  let shortenRomanNumeralDigits = (num) => {
        return num + findRomanNumeralDigit(5*romanNumeral[num]);
  }

  let higherRomanNumeralDigits = (letter) => {
    const keys = Object.keys(romanNumeral)
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] == letter) {
        return (keys[i+1]);
      }
    }
  }

  // MAIN FUNCTION
  let ans = [];
  let romanNumeralDigit;

  // Loop through finding digits
  while (num > 0) {
    romanNumeralDigit = findRomanNumeralDigit(num);
    num = num - romanNumeral[romanNumeralDigit];
    ans = ans + romanNumeralDigit;
  
    // Shorten if there are four contiguous same character
    if (ans[ans.length-1] === ans[ans.length-2] && ans[ans.length-2] === ans[ans.length-3] && ans[ans.length-3] === ans[ans.length-4]) {
      let add = shortenRomanNumeralDigits(ans[ans.length-1]);
      ans = ans.slice(0, -4);
      ans = ans + add; 
      // Shorten more if last digit and second to the last digit are same
      if (ans[ans.length-1] === ans[ans.length-3]){
        let add2 = ans[ans.length-2] + higherRomanNumeralDigits(ans[ans.length-1]);
        ans = ans.slice(0, -3)
        ans = ans + add2
      }
    }
  }
  return ans;
}
2 Likes

Here’s my solution:

 const romanLookupTable = {
   M: 1000,
   CM: 900,
   D: 500,
   CD: 400,
   C: 100,
   XC: 90,
   L: 50,
   XL: 40,
   X: 10,
   IX: 9,
   V: 5,
   IV: 4,
   I: 1
 };
//  Set up string to capture symbols
let romanNumeral = "";

// Iterate through each key in the table once
for (const key in romanLookupTable) {
  const romanValue = romanLookupTable[key];
  // check if and how many times value is in num
  while (romanValue <= num) {
    num -= romanValue;
    romanNumeral += key;
  }
}
 return romanNumeral;
}
1 Like

Not sure about the Roman Numerals for thousands:

function convertToRoman(num) {
  let r1000Symbols = ["M", "MM", "MMM", "MV", "V", "VM", "VMM", "VMMM", "MX"];
  let r100Symbols = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
  let r10Symbols = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
  let r1Symbols = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];

  let m = Math.trunc(num / 1000);
  let c = Math.trunc((num % 1000) / 100);
  let x = Math.trunc((((num % 1000)) % 100) / 10);
  let i = Math.trunc((((num % 1000)) % 100) % 10);

  let r1000 = (m === 0) ? "" : r1000Symbols[m-1];
  let r100 = (c === 0) ? "" : r100Symbols[c-1];
  let r10 = (x === 0) ? "" : r10Symbols[x-1];
  let r1 = (i === 0) ? "" : r1Symbols[i-1];

  let rNumber = r1000+r100+r10+r1;

  return rNumber;
}

convertToRoman(1000);


3 Likes

Hello everyone!
Posting my solution here.
Yesterday I was trying to pass first on 10 based values and then applying some regex or filter to add %5 numerals (V, L, D) but after coming late to today session, the iteration from greater to lower specifying the values for exceptions (9s and 4s) seems to be more convenient.

function convertToRoman(num) {

  //create arrays for symbols and values

  const rSymbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];

  const rValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

  //define a container for the roman numeral

  var rString = ""

  //if number greater than 0

  if (num > 0){

    //iterate rValues

    for (let i=0;i<rSymbols.length; i++){

      //if num greater than rValue[i], rest it from num

      //and add char to string

      while (num >= rValues[i]){

        num -= rValues[i];

        rString += rSymbols[i]

      }

    }

  }

  //return resulting string

 return rString;

}
4 Likes

You guys wrote great solutions! Here’s mine, I had fun figuring it out :upside_down_face:

function convertToRoman(num) {

const romanNumeral = {
    1000: "M",
    500: "D",
    100: "C",
    50: "L",
    10: "X",
    5: "V",
    1: "I"
}

let roman = "";

let i = 1000;

if (num >= i) {
    roman += romanNumeral[i].repeat(num / i);
    num %= i;
}
i /= 10;

function recursiveConvertToRoman(i) {

    if (i < 1) {
        return "";
    } else {
        if (num >= i) {

            if (num < i * 4) {
                roman += romanNumeral[i].repeat(num / i);
            } else if (num < i * 5) {
                roman += romanNumeral[i] + romanNumeral[i * 5];
            } else if (num < i * 6) {
                roman += romanNumeral[i * 5];
            } else if (num < i * 9) {
                roman += romanNumeral[i * 5] + romanNumeral[i].repeat((num - i * 5) / i);
            } else if (num >= i * 9) {
                roman += romanNumeral[i] + romanNumeral[i * 10];
            }
            num %= i;
        }

        return recursiveConvertToRoman(i / 10);
    }
}

recursiveConvertToRoman(i);
return roman;
}

console.log(convertToRoman(36));
2 Likes

Here’s my “Roman Numerals” adventure:

(Sorry, this is gonna be a long post, I’ll explain the journey before I post my solution in the end.)

I knew Roman numerals have signs for 1000, 500, 100 etc. and they usually are added up from left to right, with some exceptions (like 9 - IX instead of VIIII).
So I decided to first get the 1000s, 500s etc. from left to right and deal with the exceptions later. (Bad idea… - Have I mentioned I’m allergic to maths? )

I also started with putting the letters and corresponding numbers into a comment for reference.

Here’s my first step:

function convertToRoman(num) {

let Ms = Math.floor(num/1000);
if(num/1000 > 0) {
   num = num%1000;
};
let Ds = Math.floor(num/500);
if(num/500 > 0) {
   num = num%500;
};
let Cs = Math.floor(num/100);
if(num/100 > 0) {
   num = num%100;
};
let Ls = Math.floor(num/50);
if(num/50 > 0) {
   num = num%50;
};
let Xs = Math.floor(num/10);
if (num/10 > 0) {
  num = num%10;
}
let Vs = Math.floor(num/5);
if (num/5 > 0) {
  num = num%5;
}
let Is = num;

console.log("num: " + num + "Roms: " + Ms + Ds + Cs + Ls + Xs + Vs + Is);

 return num;
}

convertToRoman(36);

/*
1000 - M
 500 - D
 100 - C
  50 - L
  10 - X
   5 - V
   1 - I
*/

Next, I decided to shorten the code, because it’s repetitive.
I chose arrays, because they can easily be accessed in loops.

let romanLetters = [["M",0], ["D",0], ["C",0], ["L",0], ["X",0], ["V",0], ["I",0]];
let romanArray = [1000, 500, 100, 50, 10, 5, 1];

function countThem(counter, romanNumber) {
  romanLetters[counter][1] = Math.floor(num/romanNumber);
  if (num/romanNumber > 0) {
    num = num%romanNumber;
  };
  console.log(romanLetters[counter][1] + " - " + num);
};

for (let i=0; i < romanLetters.length; i++){
  countThem(i, romanArray[i]);
};

Next was the hardest part.
I looped through the romanLetters array to add the letters to a string variable.
Of course, now it was time to deal with the exceptions.
The exceptions come up when my code counts 4, eg. 4 Is in 9: VIIII, which needs to be converted to IX.
So I added some if else statements, and it worked for some numbers, but not for all.
I checked some console logs of numbers that worked and didn’t work.
For example:
55
M D C L X V I
0 0 0 1 0 1 0
→ LV
But:
19
M D C L X V I
0 0 0 0 1 1 4
→ XVIIII
I thought I could solve it by checking wether the number is 4, and if it is, add to the string this letter once + the one at [i-2] → IX
Then I needed to prevent the V from being added to the string, so I had the code first check if the next position (as long as a next position exists) is 4, and if so, set current position to 0. And fill in the string after the check. - This worked for some numbers, but not all.

I had to think and came up with:
If before the “4 times” position, there was “0”, add the “4 times” position once + the one before.
If before the “4 times” position, there was “1”, add the “4 times” position once + the one two positions before.

44
M D C L X V I
0 0 0 0 4 0 4
should be XLIV
99
M D C L X V I
0 0 0 1 4 1 4
should be XCIX

I took a break to go for a walk, then put it into code and passed the test shortly before the live class started. Phew! (I didn’t watch live yesterday, because I first wanted to get my own palindrome checker to work, before watching an alternative solution, because I was frustrated after the regex exercises, I had had to copy and paste the solution for some of them because I couldn’t figure them out on my own. :frowning: - By the way, does anybody know how many people have died from regex?)

Here’s the code that passed the tests before class:

function convertToRoman(num) {
let numCopy = num;
if (num > 3999) {
  return console.log("only numbers below 4000, please");
};
console.log("Your number was " + numCopy);

let romanLetters = [["M",0], ["D",0], ["C",0], ["L",0], ["X",0], ["V",0], ["I",0]];
let romanArray = [1000, 500, 100, 50, 10, 5, 1];

function countThem(counter, romanNumber) {
  romanLetters[counter][1] = Math.floor(num/romanNumber);
  if (num/romanNumber > 0) {
    num = num%romanNumber;
  };
  //console.log(romanLetters[counter][0],romanLetters[counter][1] + " - " + num);
};

// fill romanLetters Array
for (let i=0; i < romanLetters.length; i++){
  countThem(i, romanArray[i]);
};

let str="Roman is: ";
//fill string

  for (let i = 0; i<romanLetters.length; i++) {
      if (romanLetters[i+1]) { //if the next position exists
        if ((romanLetters[i+1][1] == 4)) {// and if next position is 4 times
          if((romanLetters[i][1])==0) { //and this is 0
           // add the next one + this once
            str += romanLetters[i+1][0] + romanLetters[i][0];
          } else { // and this is not 0
             //add the next + the letter before
            str += romanLetters[i+1][0] + romanLetters[i-1][0]; 
          }
        }
        else if ((romanLetters[i][1])==4){ // if this itself is 4 times
          // don't do anything, we fixed it before
        } else { // if next is not 4 times
          for (let j = romanLetters[i][1]; j>0; j--) { 
            str += romanLetters[i][0];   // add j times this position
          };
        }
      } else { // if this is last position
        // and if this position is not 4 times
        if ((romanLetters[i][1] != 4)) {
            for (let j = romanLetters[i][1]; j>0; j--) { 
              str += romanLetters[i][0];   // add j times this position
            };
        }
      };
  };

console.log(str);
num = str.replace("Roman is: ", "");
//console.log(num);
return num;
}

convertToRoman(36); 

/*
1000 - M
 500 - D
 100 - C
  50 - L
  10 - X
   5 - V
   1 - I
*/

As you see, it has a horrible “if-else” monster!! I wasn’t satisfied with this.
I had spent hours on it, and Ramón passed the project without monster code in half an hour!

After class I took another break and thought I could try to make my code simpler, if I added the ‘exception numbers’ to my arrays, similar to the way it was done in class.
Now it looks much better:

function convertToRoman(num) {
let numCopy = num;
if (num > 3999) {
  return console.log("only numbers below 4000, please");
};
console.log("Your number was " + numCopy);

let romanLetters = [["M",0], ["CM",0], ["D",0], ["CD",0], ["C",0], ["XC",0], ["L",0], ["XL",0], ["X",0], ["IX",0], ["V",0], ["IV",0], ["I",0]];
let romanArray = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

function countThem(counter, romanNumber) {
  romanLetters[counter][1] = Math.floor(num/romanNumber);
  if (num/romanNumber > 0) {
    num = num%romanNumber;
  };
  //console.log(romanLetters[counter][0],romanLetters[counter][1] + " - " + num);
};

// fill romanLetters Array
for (let i=0; i < romanLetters.length; i++){
  countThem(i, romanArray[i]);
};
//console.log(romanLetters);

let str="Roman is: ";
//fill String
for (let i = 0; i<romanLetters.length; i++) {
  for (let j = romanLetters[i][1]; j>0; j--) { 
            str += romanLetters[i][0];   
          };
};

console.log(str);
num = str.replace("Roman is: ", "");
//console.log(num);
return num;
}

convertToRoman(97); 

/*
1000 - M
 500 - D
 100 - C
  50 - L
  10 - X
   5 - V
   1 - I
*/

I just realized I should check my use of semicolons…
I guess one might improve the code further by merging the arrays into one, like [[1000, “M”,0], [900, “CM”,0] etc. ], and change the rest of the code accordingly.
But I’m not gonna try that. I’m done for today and I think I need to repeat ES6 tomorrow. So I will leave it as it is.
(I’m so tired now, I hope I didn’t write nonsense in this post… ^^’ )

2 Likes

reversed function code:

function reversed(str){
let i=20000
while(i>=0){

i--;

if(convertToRoman(i) == str){

  return i

}


}
1 Like

This one was a bit of a struggle at first, and I guess it actually ended up similar in essence to Ramon’s solution. Here it is:

function convertToRoman(num) {
  const romanNumerals = {
      1: 'I',
      4: 'IV',
      5: 'V', 
      9: 'IX',
      10: 'X',
      40: 'XL', 
      50: 'L', 
      90: 'XC',
      100: 'C',
      400: 'CD',
      500: 'D',
      900: 'CM', 
      1000: 'M', 
  };
  
  /*
  Reverse the order of numbers as JS objects are automatically
  sorted when looping over them, and we want to start from
  the largest number first
  */
  let numbers = Object.keys(romanNumerals).reverse();

  let result = '';   
  for (let key of numbers) {
      while (num >= +key) {
        result += romanNumerals[key];
        num -= +key;
      }
  }
  return result;
}
1 Like

function convertToRoman(num) {
let result=’’;
let obj1={M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
for(let key in obj1)
{
while(num>=obj1[key])
{
result+=key;
num=num-obj1[key];
}
}
return result;
}

2 Likes

Here’s my code :slight_smile:

function convertToRoman(num) {
  let amount = 0;
  
  const romanToNum = {
    1 : 'I', 2:'II', 3: 'III', 4:'IV', 5: 'V', 6:'VI', 7:'VII', 8:'VIII', 9:'IX', 10:'X', 20:'XX', 30:'XXX', 40:'XL', 50:'L', 60:'LX', 70:'LXX', 80:'LXXX', 90:'XC', 100:'C', 200:'CC', 300:'CCC', 400:'CD', 500:'D', 600:'DC', 700:'DCC', 800:'DCCC', 900:'CM', 1000:'M', 2000:'MM', 3000:'MMM'
  }

  const thousands = (num) => {
    return Math.trunc(num/1000) * 1000;    
  }

  const hundreds = (num) => {
    return Math.trunc(num/100) * 100;
  }

  const tens = (num) => {
    return Math.trunc(num/10) * 10;
  }

let romanNumeral = [];
  
  while(num > 0){

    if ((num - 1000) > 0){
    amount = thousands(num)
    romanNumeral.push(romanToNum[amount])
    num = num - amount;
  }else if((num - 100) > 0){
    amount = hundreds(num)
    romanNumeral.push(romanToNum[amount])
    num = num - amount;
  }else if ((num -10) > 0){
    amount = tens(num)
    romanNumeral.push(romanToNum[amount])
       num = num - amount;

  }else{
    romanNumeral.push(romanToNum[num])
    num = 0;
  }

  }
  
return romanNumeral.join('');
     

}
console.log(convertToRoman(36));
console.log(convertToRoman(3999));

Lots of creative solutions here!

I tried to solve this with recursion. I’m pretty sure the Romans designed their number system with recursion in mind :wink: I think my switch statement could be more compact …

`let roman_numerals = [‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’]

function convertToRoman(num, index=0) {
if (num==0) {
return ‘’;
}
const this_digit = num % 10;
let str = ‘’;

switch(this_digit) {
case 3: str += roman_numerals[index];
case 2: str += roman_numerals[index];
case 1: str += roman_numerals[index];
break;
case 8: str += roman_numerals[index];
case 7: str += roman_numerals[index];
case 6: str += roman_numerals[index];
case 5: str = roman_numerals[index+1]+str;
break;
case 4: str += roman_numerals[index];
str += roman_numerals[index+1];
break;
case 9: str += roman_numerals[index];
str += roman_numerals[index+2];
}

return convertToRoman(Math.trunc(num/10),index+2) + str;
}`

1 Like

I broke the problem down into multiple functions so lower numbers don’t have to pass through the functions for higher numbers, much like the Roman Numerals link on the project said. I’ve successfully passed numbers to the function as high as 600,000,000, but the FCC platform warns of a possible infinite loop for numbers 700mil and higher, but this is a built-in safety net of the platform for when something takes longer than the platform thinks it should take.

  while (num >= 1000) {
    converted += "M"; 
    num -= 1000;
  }
  return hundreds(num, converted);
}

function hundreds(num, converted="") {
  while (num >= 900) {
    converted += "CM"; 
    num -= 900;
  }
  while (num >= 500) {
    converted += "D"; 
    num -= 500;
  }
  while (num >= 400) {
    converted += "CD"; 
    num -= 400;
  }
  while (num >= 100) {
    converted += "C"; 
    num -= 100;
  }
  return tens(num, converted);
}

function tens(num, converted="") {
  while (num >= 90) {
    converted += "XC"; 
    num -= 90;
  }
  while (num >= 50) {
    converted += "L"; 
    num -= 50;
  }
  while (num >= 40) {
    converted += "XL"; 
    num -= 40;
  }
  while (num >= 10) {
    converted += "X"; 
    num -= 10;
  }
  return ones(num, converted);
}

function ones(num, converted="") {
  while (num >= 9) {
    converted += "IX"; 
    num -= 9;
  }
  while (num >= 5) {
    converted += "V"; 
    num -= 5;
  }
  while (num >= 4) {
    converted += "IV"; 
    num -= 4;
  }
  while (num >= 1) {
    converted += "I"; 
    num -= 1;
  }
 return converted;
}

function convertToRoman(num) {
  if (num >= 1000) {
    return thousands(num);
  } else if (num >= 100) {
    return hundreds(num);
  } else if (num >= 10) {
    return tens(num);
  } else {
    return ones(num);
  }
}

console.log(convertToRoman(3999));```

I tried it with a lookup table.
For example 26 : second digit(2) =XX + first digit (6) = VI, would be XXVI.
That’s what I ended with:

const Roman={
  0:['there is no 0','I','II','III','IV','V','VI','VII','VIII','IX'],
  1:['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC'],
  2:['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM'],
  3:['','M','MM','MMM','toBig'],
  }
  //the lookupTable for the Roman numerals

function convertToRoman(num) {
let romanNumber="";
do{
  let digits=Math.floor(Math.log10(num)); //get the digits

  let tens=Math.pow(10,digits)// get the tens? 10/100/1000

  romanNumber+=Roman[digits][Math.floor(num/tens)]////assemble the RomanNumeral
  num=num%tens; //assign the remainder as the new num
}while (num>0)//end the loop when 0
 
 return romanNumber;
}

convertToRoman(115);

1 Like

Here’s the code I had posted in the Discord channel. I see now that using arrays or objects to store the number relationships to the Roman numeral symbol would allow me to loop instead of repeating my code constantly:

function convertToRoman(num) {
  let romanNumeral = "";
  while (num >= 1000) {
    romanNumeral += "M";
    num -= 1000;
  } 
  while (num >= 900) {
    romanNumeral += "CM";
    num -= 900;
  }
  while (num >= 500) {
    romanNumeral += "D";
    num -= 500;
  }
  while (num >= 400) {
    romanNumeral += "CD";
    num -= 400;
  }
  while (num >= 100) {
    romanNumeral += "C";
    num -= 100;
  }
  while (num >= 90) {
    romanNumeral += "XC";
    num -= 90;
  }
  while (num >= 50) {
    romanNumeral += "L";
    num -= 50;
  }
    while (num >= 40) {
    romanNumeral += "XL";
    num -= 40;
  }
  while (num >= 10) {
    romanNumeral += "X";
    num -= 10;
  }
  while (num >= 9) {
    romanNumeral += "IX";
    num -= 9;
  }
  while (num >= 5) {
    romanNumeral += "V";
    num -= 5;
  }
  while (num >= 4) {
    romanNumeral += "IV";
    num -= 4;
  }
  while (num <= 3 && num != 0) {
    romanNumeral += "I";
    num -= 1;
  }
 return romanNumeral;
}
1 Like

Hi!, greetings,
my solution uses a two-dimensional matrix to solve the problem.

const getRomanNumerals = (number) => {
  
// Empty string counts for our 0, romans do not have!
const ROMAN_NUMERALS = [
       ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],
       ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],
       ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],
       ["", "M", "MM", "MMM"]
     ];

// Break number into power of tens
 const getDecimals = (number) => {
   let i = 0;
   let numberDecimals = [];
   let next = Math.trunc(number / Math.pow(10,i));
   while (next != 0) {
     numberDecimals[i] = next % 10;
     i++;
     next = Math.trunc(number / Math.pow(10,i));
   }
   return numberDecimals;
 }
 
// Convert each decimal to its roman equivalent
// Index gives the power, value the numeral, with empty string for 0
let romanNumbers = getDecimals(number).map( (value, index) => ROMAN_NUMERALS[index][value])

// Recompose number into roman numeral  
return romanNumbers.reverse().join("")

} 

This is my solution
function convertToRoman(num){
let result="";
let symbol=[‘M’,‘CM’,‘D’,‘CD’,‘C’,‘XC’,‘L’,‘XL’,‘X’,‘IX’,‘V’,‘IV’,‘I’];
let symbolValue=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
;
for (let i=0; i<symbol.length; i++){

while(num>=symbolValue[i]){
result +=symbol[i];
num -= symbolValue[i];
}

}
return result;
}

1 Like