Short JS solution


  • 3
    R
    var romObj = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
    var romanToInt = function(str) {
        var sum = 0; 
        for(var i = 0; i < str.length; i++) {
            rom1 = romObj[str.substring(i,i+1)];
            rom2 = romObj[str.substring(i+1,i+2)];
            if(str.substring(i+1,i+2) !== "" && rom1 < rom2) {
                sum += rom2 - rom1;
                i++;
            } else 
                sum += rom1;
        }
        return sum;
    };

Log in to reply
 

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