Leetcode 2011. Final Value of Variable After Performing Operations
Given an array of strings operations
containing a list of operations on a variable X
that start at 0
, determine the final value of X
after performing all the operations. Each operation is a string that can be one of the following: "--X"
, "X--"
, "++X"
, "X++"
.
"++X"
and "X++"
increments the value of X
by 1."--X"
and "X--"
decrements the value of X
by 1.operations
array?
operations
array will be one of the four valid operations.X
?
X
is always 0.X
to 0.operations
array.X
accordingly:
X
if the operation is "++X"
or "X++"
.X
if the operation is "--X"
or "X--"
.X
after applying all operations.Here’s the implementation of the plan in C++:
#include <vector>
#include <string>
int finalValueAfterOperations(std::vector<std::string>& operations) {
int X = 0;
for (const std::string& operation : operations) {
if (operation == "++X" || operation == "X++") {
X++;
} else if (operation == "--X" || operation == "X--") {
X--;
}
}
return X;
}
X
as 0.operations
vector.X
:
"++X"
or "X++"
, increment X
by 1."--X"
or "X--"
, decrement X
by 1.X
.operations
array.operations
array and each operation (increment/decrement) is performed in constant time.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?