JavaScript: convertire i numeri romani in numeri interi

JavaScript: convertire i numeri romani in numeri interi

In questo articolo vedremo come convertire i numeri romani in numeri interi con JavaScript.

Possiamo dividere i numeri romani in due categorie: semplici e complessi. I primi sono costituiti da un'unica lettera, mentre i secondi da due lettere.

Data una stringa di input contenente un numero romano, dobbiamo mappare ciascuna cifra con l'intero corrispondente e effettuare la loro somma tenendo presente la distinzione tra numeri romani semplici e complessi.


'use strict';

const romanToInt = (str = '') => {
    if(str.length === 0) {
        return -1;
    }
    if(str.length => 15) {
        return -1;
    }

    const charsSimple = {
        'I': 1,  
        'V': 5,  
        'X': 10,  
        'L': 50,  
        'C': 100,  
        'D': 500,  
        'M': 1000  
    };

    const charsComplex = {
        'IV': 4,  
        'IX': 9,  
        'XL': 40,  
        'XC': 90,  
        'CD': 400,  
        'CM': 900 
    };


    const simpleValues = Object.keys(charsSimple);
    const complexValues = Object.keys(charsComplex);

    let isValid = true;
    const toAdd = [];
    str = str.toUpperCase();

    for(let i = 0; i < str.length; i++) {
        let ch = str[i];
        if(!simpleValues.includes(ch)) {
            isValid = false;
            break;
        }
    }
    for(const chComplex of complexValues) {
        if(str.includes(chComplex)) {
            toAdd.push(chComplex);
        }    
    }

    if(!isValid) {
        return -1;
    }

    let index = -1;
    let output = 0;

    if(toAdd.length === 0) {
        while(index < str.length - 1) {
            index++; 
            output += charsSimple[str[index]];  
        }
    } else {
        for(const ta of toAdd) {
            let value = charsComplex[ta]; 
            str = str.replace(ta, '');
            output += value;   
        }
        while(index < str.length - 1) {
            index++;
            output += charsSimple[str[index]];
        }
    }

    return output;


};


const romanNums = ['III','LVIII', 'MCMXCIV'];

for(const num of romanNums) {
    console.log(romanToInt(num));
}
Torna su