LeetCode problem#2011
Final Value of Variable After Performing Operations
Solved in 2 languagesC#Java
Solution
16 lines
1public class Solution {
2 public int FinalValueAfterOperations(string[] operations) {
3 int x = 0;
4 foreach (var operation in operations)
5 {
6 if (operation.Equals("X++") || operation.Equals("++X")) {
7 x++;
8 }
9 else // assumption: cannot be something other than --X and X--
10 {
11 x--;
12 }
13 }
14 return x;
15 }
16}1class Solution {
2 public int finalValueAfterOperations(String[] operations) {
3 int x = 0;
4
5 for (int i = 0; i < operations.length; i++) {
6 if (operations[i].charAt(1) == '+') {
7 x++;
8 }
9 else {
10 x--;
11 }
12 }
13
14 return x;
15 }
16}Want a walkthrough of this C# solution?
Get a step-by-step explanation of the idea behind the code.
Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.