Skip to content

Instantly share code, notes, and snippets.

@MunimIftikhar
Last active November 8, 2022 18:27
Show Gist options
  • Select an option

  • Save MunimIftikhar/654c1253c479278f7564093115eb4ce2 to your computer and use it in GitHub Desktop.

Select an option

Save MunimIftikhar/654c1253c479278f7564093115eb4ce2 to your computer and use it in GitHub Desktop.
freeCodeCamp: Roman Numeral Convertor

Problem Statement

Convert the given number into a roman numeral. All roman numerals answers should be provided in upper-case.

Constraints

  • Given number is an arabic numeral ranges starting from 1.

Input example #1

44

Expected output #1

"XLIV"

Input example #2

649

Expected output #2

"DCXLIX"

Solution code

// Solution function
function convertToRoman(num) {
    // Store common numerals in arabicNumerals and commonNumerals array 
    let arabicNumerals = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
    let commonNumerals = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"];
    // Use romanNumeral to store the results
    let romanNumeral = "";

    // Recursively find the roman numeral
    function convert(num) {
        // return if num is equal to 0
        if (num == 0) {
            return
        }
        // Loop through the common numerals, extract the common numeral from num and call the convert function
        for (let i = 0; i < arabicNumerals.length; i++) {
            // Check if num is equal to arabicNumerals[i]
            // Check if num is bigger than arabicNumerals[i] and i is equal to arabicNumerals.length - 1
            // Check if num is in range of arabicNumerals[i] and arabicNumerals[i+1]
            if ((num == arabicNumerals[i]) || (num > arabicNumerals[i] && i == arabicNumerals.length - 1) || (num > arabicNumerals[i] && num < arabicNumerals[i + 1])) {
                // Add common roman numeral to romanNumeral variable
                romanNumeral += commonNumerals[i];
                // Extract arabicNumerals[i] from num
                num = num - arabicNumerals[i];
                // Call convert recursively
                convert(num);
            }
        }
    }
    convert(num)
    // Return romanNumeral
    return romanNumeral;
}

// Driver code
console.log(convertToRoman(3999));
convertToRoman(3999);

Problem link

freeCodeCamp Roman Numeral Converter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment