Easy to understand Javascript solution


  • 1
    H

    This solution favors readability over conciseness.

    /**
     * @param {string} s
     * @return {number}
     */
    var romanToInt = function(s) {
        const romans = {
            I: 1,
            V: 5,
            X: 10,
            L: 50,
            C: 100,
            D: 500,
            M: 1000
        };
        
        let total = 0;
        
        for (let i = 0; i < s.length; i++) {
            const num = s[i];
            const next = s[i + 1];
            
            switch(num) {
                case 'I':
                    total += next == 'V' || next == 'X' ? -1 : romans[num];
                    break;
                case 'X':
                    total += next == 'L' || next == 'C' ? -10 : romans[num];
                    break;
                case 'C':
                    total += next == 'D' || next == 'M' ? -100 : romans[num];
                    break;
                default:
                    total += romans[num];
            }
        }
        
        return total;
        
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.