[Leetcode]2011. Final Value of Variable After Performing Operations

2024. 7. 26. 08:47java/javaAlgorithm

1. problem : 

https://leetcode.com/problems/final-value-of-variable-after-performing-operations/description/

 

 

2. solution 1 : 

class Solution {
    public int finalValueAfterOperations(String[] operations) {
    int x = 0;
        for (int i = 0; i < operations.length; i++) {
            if (operations[i].contains("+")) {
                x++;
            } else if (operations[i].contains("-")) {
                x--;
            }
        }
        return x;
    
    
    }
}

java라는 언어를 배우는 도중, 언어의 이해를 높이기 위해 algorithm 문제도 같이 풀고 있다. 

이 문제는 String[]배열에 들어있는 원소에 "+"가 들어있다면 x값을 1 더해준다. 아니라면 -1 해준다. 

이때, contains라는 method가 사용된다. 

Solution이라는 클래스안에 finalValueAfterOperations라는 메서드를 만들었다. 

그럼 이 클래스는 SolutionMain으로 실행하면 되겠다