2022/12/20

LeetCode 2011. Final Value of Variable After Performing Operations

問題:取得運算子後的結果,初始化數值等於0
解法:foreach走訪,透過indexOf判斷為--,則數值減1;反之加1 JavaScript
/**
 * @param {string[]} operations
 * @return {number}
 */
var finalValueAfterOperations = function (operations) {
    let x = 0;
    operations.forEach(s => {
        if (s.indexOf("--") >= 0) {
            x -= 1;
        } else {
            x += 1;
        }
    })

    return x;
};