Free Code Camp’s Bonfire Challenge Roman Numeral Converter

Posted by

The objective of this challenge is to convert a given number into a roman numeral (the argument num).  The only requirement given for the challenge is to make sure all roman numeral answers be provided in upper-case  lettering. Here’s the code that was given to us:

function convertToRoman(num){
return num;
}
convertToRoman(36);

Here’s the process that helped me to achieve my final solution to the problem.

  • One of the first things I did was do some research to find an example algorithm to help me solve this problem.  I found this one here.  I then sat down and wrote out my code/solution.  My first plan of action was to create an object containing both the numerical value  and its equivalent roman numeral:
    var romanObj={M:1000, CM:900, D:500, C:100, XC:90, L:50, XL:40, X:10, IX: 9, V:5, IV:4, I:1};
    
  • Make two variables: The first variable was an empty string that would contain the roman numeral when we’re finished.
     var rN="";
    

The second variable contain individual  items in the romanObj object.

 var x;
  • Next,  I wrote a for/in loop to iterate over the properties in  romanObj. Then write a while loop within the for/in loop.  The while loop keeps the loop going as long as num is larger than zero.  While the loop is going, the appropriate key from romanObj is added to the string rN and the corresponding value is subtracted from num. This causes num to shrink as the appropriate roman numerals are found. The process is complete  when num equals zero at which point the correct roman numeral string has been created.
  for(x in romanObj){
    while(num >= romanObj[x]){
      rN += x;
      num -= romanObj[x];
    }
  }
 return rN;
}

In closing, this challenge was a hard for me because not much information was given to solve the problem. Nevertheless, I did learn more about for loops involving objects and the usage of while loops. Here’s my final solution to this problem:


function convertToRoman(num) {

  var romanObj={M:1000, CM:900, D:500, C:100, XC:90, L:50, XL:40, X:10, IX: 9, V:5, IV:4, I:1};
  var rN="";
  var x;
  for(x in romanObj){
    while(num >= romanObj[x]){
      rN += x;
      num -= romanObj[x];
    }
  }

 return rN;

}

convertToRoman(36);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s