pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

棒球比赛 #1014

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

682. 棒球比赛

/**
 * @param {string[]} ops
 * @return {number}
 */
var calPoints = function(ops) {
    const stack = [];
    ops.forEach(value => {
        let len = stack.length,
            sum;
        if(value == "+" && len > 1) {
            sum = stack[len-1] + stack[len-2];
            stack.push(sum);
        }else if(value == "D" && len > 0) {
            sum = stack[len-1] * 2;
            stack.push(sum);
        }else if(value == "C" && len > 0) {
            stack.pop();
        }else {
            stack.push(parseInt(value));
        }
    });
    return stack.reduce((acc, current) => acc += current);
};