[LeetCode] Baseball Game - JavaScript

이은빈 EUNBIN·2021년 4월 27일
0
post-thumbnail

👩🏻‍💻 문제

LeetCode #682 Baseball Game



👩🏻‍💻 풀이

var calPoints = function(ops) {
    let result = [];
    
    for(let i = 0; i < ops.length; i++) {
        if(ops[i] === "C") {
            result.pop();
        } else if(ops[i] === "D") {
            result.push(2 * result[result.length-1]);
        } else if(ops[i] === "+") {
            result.push(parseInt(result[result.length-2]) + parseInt(result[result.length-1]));
        } else {
            result.push(parseInt(ops[i]));
        }
    }
    
    return result.reduce((acc, cur) => acc + cur);
};
// 다른 분의 코드
var calPoints = function(ops) {
    const pts = [];
  
    ops.forEach((op) => {
        switch (op) {
            case '+':
                pts.push(pts[pts.length - 1] + pts[pts.length - 2]);
                break;
            case 'D':
                pts.push(pts[pts.length - 1] * 2);
                break;
            case 'C':
                pts.pop();
                break;
            default:
                pts.push(parseInt(op));
                break;
        }
    });
  
    return pts.reduce((acc, pt) => acc + pt);
};
profile
Frontend Engineer & Value Creator

0개의 댓글