Quick&Dirty Accepted JS Solution in 10 lines. Shortest Maybe?


  • 0

    It is actually almost the same as other solutions using stack and calculate upon operators, just play some fun using some javascript feature like mapping a function in a object and non-number checking using isNaN.

    Note that since we need to pop the operands twice, the parameters order is b, a instead of a,b

    Leave a comment if you have further question. Anyway, don't write code like this in real work :P

    /**
     * Complex: O(n)
     * Runtime: 132ms
     * Tests: 20 test cases passed
     * Rank: S
     * Updated: 2015-06-11
     */
    var evalRPN = function(tokens) {
        var stack = [];
        var map = Object.create(null);
        map['+'] = function(b, a) { return a + b; };
        map['-'] = function(b, a) { return a - b; };
        map['*'] = function(b, a) { return a * b; };
        map['/'] = function(b, a) { return ~~(a / b); };
        for (var i = 0; i < tokens.length; i++)
            stack.push(isNaN(tokens[i]) ? map[tokens[i]](parseInt(stack.pop(), 10), parseInt(stack.pop(), 10)) : tokens[i]);
        return parseInt(stack.pop(), 10);
    };

Log in to reply
 

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