LeetCode #2011. Final Value of Variable After Performing Operations

LeetCode #2011. Final Value of Variable After Performing Operations

Question : There is a programming language with only four operations and one variable X:

++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.

Initially, the value of X is 0.

Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.

Solution

To solve this question,basically you need to initialize the value of X to 0, in my case I am using ageCount as the variable name simply because today is my birthday ):

Then we loop over the array using a forloop. In the forloop we initialize int i = 0and then loop until i < length of array making an increment of plus one after the condition is check. In the condition we compare the value of the array item to see if it equals our operator and then increase/decrease the ageCount. Remember when comparing string we use value1.equals(value2).

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int ageCount = 0;
        for(int i= 0;i<operations.length;i++){
            if(operations[i].equals("++X") || operations[i].equals("X++")){
                ageCount++;
            }else{
                ageCount--;
            }
        }
        return ageCount;


    }
}

Here is the link to the question