Final Value of Variable After Performing Operations

easy strings simulation array

Problem

A tiny language has one integer variable X that starts at 0. Each operation is one of "++X", "X++", "--X", or "X--": the two + signs add 1 and the two - signs subtract 1, regardless of which side of X they sit on. Given the list of operations, return the final value of X after performing all of them in order.

Inputoperations = ["--X","X++","X++"]
Output1
0 → −1 (--X) → 0 (X++) → 1 (X++). Final value is 1.
Inputoperations = ["X++","++X","--X","X--"]
Output0
Two increments and two decrements cancel out, leaving 0.

def final_value(operations):
    x = 0
    for op in operations:
        if op[1] == "+":
            x += 1
        else:
            x -= 1
    return x
function finalValueAfterOperations(operations) {
  let x = 0;
  for (const op of operations) {
    if (op[1] === "+") {
      x += 1;
    } else {
      x -= 1;
    }
  }
  return x;
}
int finalValueAfterOperations(String[] operations) {
    int x = 0;
    for (String op : operations) {
        if (op.charAt(1) == '+') {
            x += 1;
        } else {
            x -= 1;
        }
    }
    return x;
}
int finalValueAfterOperations(vector<string>& operations) {
    int x = 0;
    for (string& op : operations) {
        if (op[1] == '+') {
            x += 1;
        } else {
            x -= 1;
        }
    }
    return x;
}
Time: O(n) Space: O(1)