Javascript Solution with a Hash


  • 0
    R
    
    var romanToInt = function(s) {
        let dictionary = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        };
        
        if (typeof s !== "string") {
            return null;
        }
        
        if (s.length === 1) {
            return dictionary[s];
        }
        
        let res = 0;
        
        for (let i = 0; i < s.length - 1; i++) {
            if (dictionary[s[i + 1]] > dictionary[s[i]]) {
                res -= dictionary[s[i]];
            } else {
                res += dictionary[s[i]];
            }
        }
        
        return res + dictionary[s[s.length - 1]];
    };
    
    
    Suggestions always appreciated!

Log in to reply
 

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