commit 630d68a4840a8ae40c063ce36115f401f7273005
parent 293c6cb70524a1cbc7c8947c2c6e24db02bbd4c4
Author: Jack Sangdahl <jack@pngu.org>
Date: Sun, 19 Oct 2025 19:48:51 -0600
2011. final value of variable after performing operations
Diffstat:
2 files changed, 61 insertions(+), 0 deletions(-)
diff --git a/final_value_var_op.c b/final_value_var_op.c
@@ -0,0 +1,35 @@
+// 2011. Final Value of Variable After Performing Operations
+#include "leetcode.h"
+
+/*
+ * 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, and '--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.
+ */
+
+int finalValueAfterOperations(char **operations, int operationsSize) {
+ int x = 0;
+ for (int i = 0; i < operationsSize; i++) {
+ char *op = operations[i];
+ if (!strcmp(op, "X++") || !strcmp(op, "++X"))
+ x++;
+ else
+ x--;
+ }
+ return x;
+}
+
+int main() {
+ char *o1[] = {"--X", "X++", "X++"};
+ char *o2[] = {"++X", "++X", "X++"};
+ char *o3[] = {"X++", "++X", "--X", "X--"};
+ printf("%d\n",
+ finalValueAfterOperations((char **)o1, ARRAY_SIZE(o1))); // expect: 1
+ printf("%d\n",
+ finalValueAfterOperations((char **)o2, ARRAY_SIZE(o2))); // expect: 3
+ printf("%d\n",
+ finalValueAfterOperations((char **)o3, ARRAY_SIZE(o3))); // expect: 0
+}
diff --git a/final_value_var_op.py b/final_value_var_op.py
@@ -0,0 +1,26 @@
+# 2011. Final Value of Variable After Performing Operations
+
+"""
+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, and '--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.
+"""
+
+
+class Solution(object):
+ def finalValueAfterOperations(self, operations):
+ """
+ :type operations: List[str]
+ :rtype: int
+ """
+ return sum(1 if op[1] == "+" else -1 for op in operations)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.finalValueAfterOperations(operations=["--X", "X++", "X++"]))
+ print(obj.finalValueAfterOperations(operations=["++X", "++X", "X++"]))
+ print(obj.finalValueAfterOperations(operations=["X++", "++X", "--X", "X--"]))