leetcode682: js achieve a baseball game

Title: You are now a baseball game scorer.
Given a list of strings, each string can be one of four types:
1. Integer (a score): Direct represents the number of points you get in this round.
2. "+" (a score): Indicates the current round score obtained is valid round score of the first two rounds combined.
3. "D" (a score): Indicates the current round score obtained is valid round bout before scoring twice.
4. "C" (an operation, this is not a round scores): you get a valid final round score is invalid and should be removed.
Each round of operations are permanent, may have an impact after the previous round and round.
You need to return your score in all rounds combined.
Example 1:
Input: [ "5", "2 ", "C", "D", "+"]
Output: 30
Example 2:
Input: [ "5", "- 2", "4", "C "," D "," 9 "," + "," + "]
output: 27

let originArr = ["5", "-2", "4", "C", "D", "9", "+", "+", "+"];
const fun = (arr) => {
    originArr.forEach((item, index) => {
        if (item === 'C') {
            originArr.splice(index - 1, 2);
            fun(originArr);
        } else if (item === 'D') {
            originArr[index] = Number(originArr[index - 1]) * 2;
            fun(originArr);
        } else if (item === '+') {
            originArr[index] = Number(originArr[index - 1]) + Number(originArr[index - 2]);
            fun(originArr);
        }
    });
    return originArr.reduce((a, b) => {
        return Number(a) + Number(b);
    });
};
const res = fun(originArr);
console.log(res);
He published 194 original articles · won praise 18 · views 50000 +

Guess you like

Origin blog.csdn.net/sinat_41747081/article/details/104102280