2011. Final Value of Variable After Performing Operations

Leetcode link

题目简介

/**
 * @param {string[]} operations
 * @return {number}
 */

本题参数 operations 包含四种操作:"++X", "X++", "--X", "X--"

X 的初始值为 0,要求我们求出在经过所有 operations 之后 X 的值

解题思路

直接一个循环解了

Javascript

/**
 * @param {string[]} operations
 * @return {number}
 */
var finalValueAfterOperations = function(operations) {
    let res = 0

    for(const op of operations) {
        if(op[1] === '+') {
            res++
        } else {
            res--
        }
    }

    return res
};

results matching ""

    No results matching ""