# 2011. Final Value of Variable After Performing Operations [JavaScript] LeetCode 2011 ## 題目概要 - 給定一個陣列 operations,裡面包含著所有操作,x++ 或者 ++x 都代表將 x + 1; 反之 x-- 或 --x 都代表 x - 1,求經過計算後的結果為何。 ``` Example 1: Input: operations = ["--X","X++","X++"] Output: 1 Explanation: The operations are performed as follows: Initially, X = 0. --X: X is decremented by 1, X = 0 - 1 = -1. X++: X is incremented by 1, X = -1 + 1 = 0. X++: X is incremented by 1, X = 0 + 1 = 1. Example 2: Input: operations = ["++X","++X","X++"] Output: 3 Explanation: The operations are performed as follows: Initially, X = 0. ++X: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. X++: X is incremented by 1, X = 2 + 1 = 3. Example 3: Input: operations = ["X++","++X","--X","X--"] Output: 0 Explanation: The operations are performed as follows: Initially, X = 0. X++: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. --X: X is decremented by 1, X = 2 - 1 = 1. X--: X is decremented by 1, X = 1 - 1 = 0. ``` ## 解題技巧 - 直接判斷元素包含的是 + 還是 - ,然後將總和進行對應的運算即可。 ## 程式碼 ```js var finalValueAfterOperations = function(operations) { let sum = 0; for(const ele of operations){ if(ele.includes("+")) sum++ else sum-- } return sum; }; ``` ![](https://i.imgur.com/jxBSIHq.png)