Roman Numeral Converter - Focus on the small numbers

Hi All,

I’m new to JS and came accross this challenge today.

I think I might have accidentally stumbled accross the correct answer.

My initial idea was to get it working with all numbers <= 10 and once that was working, to work on the larger numbers by breaking them down using math functions and then performing similiar functions to those used on my <= 10 version. . In doing so I accidentally got it working with every number because of the logic used. I am sure this is probably not the most efficient way of performing the calculations but it goes to show that if you focus on smaller tasks then sometimes the bigger ones fall into place.

Any advice on my code would be great as I am flying solo in my journey so meeting people and discussing different ways of solving problems is a huge bonus! The more the merrier :slight_smile:

Keep up the amazing work all!

Shaun

  // make an object array of roman numerals and big jumps like
 // 1, 4, 5,9, 10, 40 50 60 70 80 90 100, 400, 500, 900, 1000

  // subtract from the number until it finds a match in my array? 

function convertToRoman(num) {

 var romanArr = [
 {number:1, roman: "I"},
 {number:4, roman: "IV"},
 {number:5, roman: "V"},
 {number:9, roman: "IX"},
 {number:10, roman: "X"},
 {number:40, roman: "XL"},
 {number:50, roman: "L"},
 {number:90, roman: "XC"},
 {number:100, roman: "C"},
 {number:400, roman: "CD"},
 {number:500, roman: "D"},
 {number:900, roman: "CM"},
 {number:1000, roman: "M"}
 ]


let romanAnswer = []
let remainder = 0

// you minus 1 from the number until it finds a match
//  whilst keeping a tally of the remainder. 
// Then you do the same with the remainder 
// until you have a match and rinse and repeat until your number is 0

while (num != 0)

//this checks if the number is in my above array
if (romanArr.some(e => e.number === num)) { 

  // if it is in the array, push to my romanAnswer

  romanAnswer.push(romanArr.find(o => o.number === num).roman); 

  // work out what is left to repeat process with the remainder 
  num = remainder 

  // reset the remainder
  remainder = 0 

  }  else {

    // if it doesn't match my object we +1 to the remainder
    remainder ++ 

    // -1 from our num
    num--
  }

// return the answer joined up to show as roman numeral
return romanAnswer.join("")

}

convertToRoman(8);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.