Algorithms/Java

백준 10773: 제로 (java)

Jenn28 2023. 12. 28. 21:15

스택을 사용한 문제를 풀어보고 싶어서 도전했다.


 

알고리즘

스택

 

체감 난이도

★ ★ ☆ ☆ ☆

 

다시 풀 수 있는가?

YES

 


 

전체 코드 ▼

더보기
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;

public class BOJ10773 {
    public int solution() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int K = Integer.parseInt(br.readLine());

        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < K; i++) {
            int s = Integer.parseInt(br.readLine());

            if (s == 0) {
                stack.pop();
            }
            else {
                stack.push(s);
            }
        }

        int ans = 0;
        for (int i : stack) {
            ans += i;
        }

        return ans;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new BOJ10773().solution());
    }
}