Clear Javascript Solution


  • 0
    S
    var romanToInt = function(s) {
        var mapping = {
            I: 1,
            V: 5,
            X: 10,
            L: 50,
            C: 100,
            D: 500,
            M: 1000,
        }
        
        var sum = 0;
        var prev;
        for (var i=s.length-1; i>=0; --i) {
            var curNum = mapping[s[i]];
            
            if (prev && mapping[prev] > curNum) {
                sum -= curNum;
            } else {
                sum += curNum;
            }
            
            prev = s[i];
        }
        
        return sum;
    };
    

Log in to reply
 

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