Horje
JavaScript Program to Convert a String to Roman Numerals

In this article, we will see how to convert a string to Roman numerals using JavaScript. Converting a string to Roman numerals in JavaScript is a common task when working with text data containing numeric values in Roman numeral format. Roman numerals are a numeral system used in ancient Rome, and they are still used in various contexts such as numbering book chapters, naming monarchs, or denoting particular years.

These are the following methods to convert a string to Roman numerals using JavaScript:

  • Using an Array of Values and Symbols
  • Using an object
  • Using a Map

Using an Array of Values and Symbols

  • In this approach, we are creating two arrays having values in an integer and in a string as a Roman count and one variable for storing the Roman numeral representation.
  • Iterate and check if the current num is greater than or equal to values[i] If true, add symbols[i] to the result and subtract values[i] from num. Repeat until num is no longer greater than or equal to values[i].
  • Return the result as the Roman numeral representation of the input number.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function stringToRoman(num) {
    const values = 
        [1000, 900, 500, 400, 100, 
         90, 50, 40, 10, 9, 5, 4, 1];
    const symbols = 
        ['M', 'CM', 'D', 'CD', 'C', 
         'XC', 'L', 'XL', 'X', 'IX', 
         'V', 'IV', 'I'];
    let result = '';

    for (let i = 0; i < values.length; i++) {
        while (num >= values[i]) {
            result += symbols[i];
            num -= values[i];
        }
    }

    return result;
}

const input = "2013";
const result = stringToRoman(parseInt(input));
console.log(result);

Output
MMXIII

Using an object

  • Create an object that maps Roman numeral symbols to their decimal values and an empty string to store the Roman numeral representation.
  • Iterate through the Roman numeral symbols in descending order of their decimal values. For each symbol, calculate how many times it fits into the input number and append that symbol to the result string that many times.
  • Subtract the portion of the number converted to Roman numerals from the input. Repeat this process for all symbols. And then return the result string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function stringToRoman(num) {
    let roman = {
        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
    };
    let str = '';

    for (let i of Object.keys(roman)) {
        let q = Math.floor(num / roman[i]);
        num -= q * roman[i];
        str += i.repeat(q);
    }

    return str;
}

console.log(stringToRoman(1234));

Output
MCCXXXIV

Using Recursion

Using recursion, find the largest Roman numeral less than or equal to the number and append it to the result. Recurse with the remaining value until it reaches zero. Return the concatenated Roman numerals.

Example:

JavaScript
function toRoman(num) {
    const romanNumerals = [
        { value: 1000, numeral: 'M' },
        { value: 900, numeral: 'CM' },
        { value: 500, numeral: 'D' },
        { value: 400, numeral: 'CD' },
        { value: 100, numeral: 'C' },
        { value: 90, numeral: 'XC' },
        { value: 50, numeral: 'L' },
        { value: 40, numeral: 'XL' },
        { value: 10, numeral: 'X' },
        { value: 9, numeral: 'IX' },
        { value: 5, numeral: 'V' },
        { value: 4, numeral: 'IV' },
        { value: 1, numeral: 'I' }
    ];

    if (num === 0) return '';

    for (let i = 0; i < romanNumerals.length; i++) {
        if (num >= romanNumerals[i].value) {
            return romanNumerals[i].numeral + toRoman(num - romanNumerals[i].value);
        }
    }
}


console.log(toRoman(354)); // Output: "CCCLIV"

Output
CCCLIV

Using a Map

In this approach, we utilize a Map object to store the Roman numeral symbols along with their corresponding integer values. This allows for efficient lookups and a clean implementation.

Example: This example shows the implementation of the above approach.

JavaScript
function stringToRoman(num) {
    const romanMap = new Map([
        ['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]
    ]);
    let result = '';

    for (let [symbol, value] of romanMap) {
        while (num >= value) {
            result += symbol;
            num -= value;
        }
    }

    return result;
}

console.log(stringToRoman(1987)); // Output: "MCMLXXXVII"

Output
MCMLXXXVII



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to Create Countdown Timer using React Native ? How to Create Countdown Timer using React Native ?
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
JavaScript Program to Count Number of Alphabets JavaScript Program to Count Number of Alphabets
JavaScript Program for Converting given Time to Words JavaScript Program for Converting given Time to Words
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11