2011. Final Value of Variable After Performing Operations #2318
-
|
Topics: There is a programming language with only four operations and one variable
Initially, the value of Given an array of strings Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to determine the final value of a variable Approach
Let's implement this solution in PHP: 2011. Final Value of Variable After Performing Operations <?php
/**
* @param String[] $operations
* @return Integer
*/
function finalValueAfterOperations($operations) {
$x = 0;
foreach ($operations as $op) {
if ($op[1] == '+') {
$x++;
} else {
$x--;
}
}
return $x;
}
// Test cases
// Example 1
$operations1 = ["--X", "X++", "X++"];
echo "Output 1: " . finalValueAfterOperations($operations1) . "\n"; // Expected: 1
// Example 2
$operations2 = ["++X", "++X", "X++"];
echo "Output 2: " . finalValueAfterOperations($operations2) . "\n"; // Expected: 3
// Example 3
$operations3 = ["X++", "++X", "--X", "X--"];
echo "Output 3: " . finalValueAfterOperations($operations3) . "\n"; // Expected: 0
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to determine the final value of a variable
Xafter performing a series of operations. The operations can either increment or decrement the value ofXby 1. The operations are given as an array of strings, each string being one of the following:"++X","X++","--X", or"X--". The initial value ofXis0.Approach
Xset to0.+, it indicates an increment operation; if it is-, it indicates a decrement operation.