forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
Algorithm Roman Numeral Converter
Rafael J. Rodriguez edited this page May 23, 2016
·
8 revisions
- You will create a program that converts an integer to a Roman Numeral.
- Creating two arrays, one with the Roman Numerals and one with the decimal equivalent for the new forms will be very helpful.
- If you add the numbers to the arrays that go before the new letter is introduced, like values for 4, 9, and 40, it will save you plenty of code.
- You can't have more than three consecutive Roman numerals together.
Solution ahead!
var convertToRoman = function(num) {
// Create arrays with default conversion with matching indices.
var decimalValue = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
var romanNumeral = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
//empty string variable for the final roman number
var romanized = '';
// Loop through the indices of the decimalValue array.
for (var index = 0; index < decimalValue.length; index++) {
// Continue to loop while the value at the current index will fit into numCopy
while (decimalValue[index] <= num) {
// Add the Roman numeral & decrease numCopy by the decimal equivalent.
romanized += romanNumeral[index];
num -= decimalValue[index];
}
}
return romanized;
}
// test here
convertToRoman(36);🚀 Run Code
- Read comments on code.
If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @Rafase282 @SaintPeter @benschac for your help with Algorithm: Roman Numeral Converter
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links