Leetcode

Final Value of Variable After Performing Operations

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  int finalValueAfterOperations(vector<string>& operations) {
    int ans = 0;

    for (const auto& op : operations)
      ans += op[1] == '+' ? 1 : -1;

    return ans;
  }
};

JAVA

class Solution {
  public int finalValueAfterOperations(String[] operations) {
    int ans = 0;

    for (final String op : operations)
      ans += op.charAt(1) == '+' ? 1 : -1;

    return ans;
  }
}

Python

class Solution:
  def finalValueAfterOperations(self, operations: List[str]) -> int:
    return sum(op[1] == '+' or -1 for op in operations)