Pankaj Tanwar
Published on

Final Value of Variable After Performing Operations.

––– views

Yayyy tada, I made it to Day #7. Let's see how long it goes. well, let's directly jump to the problem.

Problem of the day - Final Value of Variable After Performing Operations

Tag - Easy

Problem says, a programming language is given which has only 4 operations defined where X++ and ++X means, increment the value by 1 and X-- and --X means decrement the value by 1. Initial value is 0, final result should be returned.

Problem is pretty simple. I don't like dirty work of putting multiple if else in my code. My approach would be to just check the second index char in each value. It will either be + or - and based on this increment or decrement the result count.

My code looks like this.

class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int ans=0;
for(auto val: operations) ans += (val[1] == '+') ? 1 : -1;
return ans;
}
};

Ooops, I know I am trying to shorten my code. I like it.


You might like previous editions of my coding diary where I everyday solve a problem and share my thought process.