문제 원본: https://leetcode.com/problems/final-value-of-variable-after-performing-operations/

문제

하나의 변수 X와 오직 네 개의 연산이 있는 프로그래밍 언어가 있다.

  • ++XX++는 변수 X1만큼 증가시킨다.
  • --XX--는 변수 X1만큼 감소시킨다.

X의 초기값은 0이다.

연산 리스트인 operations 문자열 배열이 주어졌을 때, 모든 연산을 수행한 후 X의 최종 값을 반환하라.

Example 1:

Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X =  0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 =  0.
X++: X is incremented by 1, X =  0 + 1 =  1.

Example 2:

Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.

Example 3:

Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.

Constraints:

  • 1 <= operations.length <= 100
  • operations[i]"++X", "X++", "--X", "X--" 중에 하나이다.

접근 방법

그대로 operations의 모든 요소를 순회하면서 각 요소에 맞는 연산을 해주면 된다. 그 중에서도 ++X, X++일 때에는 x++, --X, X--일 때에는 x--로 묶어서 두 개의 분기로 나누고 연산을 해줬다.

풀이

Java

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;
        
        for (int i = 0; i < operations.length; i++) {
            switch (operations[i]) {
                case "X++":
                case "++X":
                    x += 1;
                    break;
                default:
                    x -= 1;
                    break;
            }
        }
        return x;
    }
}
  • Runtime: 1ms
  • Memory: 43.5MB

switch case문을 이용했는데, X++++X의 경우를 묶어서 한 번에 처리했다. 어차피 operations[i]는 한정되어 있으니, 위의 두 가지의 경우를 제외하면 감소의 경우만 남아서 default로 처리했다. 사실 x += 대신에 ++x를 써도 된다.

C#

public class Solution {
    public int FinalValueAfterOperations(string[] operations) {
        int x = 0;
        
        foreach (string op in operations)
        {
            switch (op)
            {
                case "X++":
                case "++X":
                    ++x;
                    break;
                default:
                    --x;
                    break;
            }
        }
        return x;
    }
}
  • Runtime: 76ms
  • Memory: 40.1MB

자바에서 for문을 썼다면, C#에서는 foreach문을 써봤다. 그 외에 기본적인 틀은 모두 동일하다.

Python

class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        x = 0
        
        for op in operations:
            if op == "X++" or op == "++X":
                x += 1
            else:
                x -= 1
        return x
  • Runtime: 44ms
  • Memory: 13.9MB

파이썬도 앞의 둘과 틀은 같은데, switch case문이 아니라 순수 if문을 이용해서 작성했다.

댓글남기기