[LeetCode] Final Value of Variable After Performing Operations

아르당·2026년 7월 28일

LeetCode

목록 보기
431/624
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

4가지 연산과 1개의 변수 x로만 이루어진 프로그래밍 언어가 있다.

  • ++x와 x++는 변수 x의 값을 1씩 증가시킨다.
  • --x와 x--는 변수 x의 값을 1씩 감소시킨다.

처음에 x는 0이다.
연산의 목록이 포함된 문자열 배열 operations가 주어졌을 때, 모든 연산을 수행하고 x의 최종 값을 반환해라.

Example

#1
Input: operations = ["--x", "x++", "x++"]
Output: 1

#2
Input: operations = ["++x", "++x", "x++"]
Output: 3

#3
Input: operations = ["x++", "++x", "--x", "x--"]
Output: 0

Constraints

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

Solved

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;

        for(String operation : operations){
            if(operation.charAt(1) == '+'){
                x++;
            }else{
                x--;
            }
        }

        return x;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글