Loading
Leetcode / 2011. Final Value of Variable After Performing Operations

Pick a programming language:

Here is the source code for the solution to this problem.

public class Solution {
    public int FinalValueAfterOperations(string[] operations) {
        int x = 0;
        foreach (var operation in operations)
        {
            if (operation.Equals("X++") || operation.Equals("++X")) {
                x++;
            }
            else // assumption: cannot be something other than --X and X--
            {
                x--;
            }
        }
        return x;
    }
}
class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;

        for (int i = 0; i < operations.length; i++) {
            if (operations[i].charAt(1) == '+') {
                x++;
            }
            else {
                x--;
            }
        }

        return x;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: