A simple solution in Javascript


  • 0
    B
    var romanToInt = function(str) {
        if(str.length === 0) return -1;
        var map = {};
        map.I = 1;
        map.V = 5;
        map.X = 10;
        map.L = 50;
        map.C = 100;
        map.D = 500;
        map.M = 1000;
        
        var len = str.length;
        var ret = map[str.charAt(len-1)];
        var current;
        var prev = str.charAt(len-1);
        for(var i = len-2; i >= 0; i--) {
            current = str.charAt(i);
            if(map[current] < map[prev]) {
                ret -= map[current];
            } else {
                ret += map[current];
            }
            prev = current;
        }
        return ret;
    };

Log in to reply
 

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