본문 바로가기
백준

백준 10773: 제로(java)

by unhyepnhj 2024. 7. 12.

문제


풀이

 

'가장 최근에 쓴 수' 라는 표현에 주목하자. 가장 최근에 입력된 값을 불러오려면 당연히 후입선출 구조의 스택을 사용해야 한다.

정수가 0일 경우에 가장 최근에 쓴 수를 지우는 것은 pop, 아닐 경우 해당 수를 쓰는 것은 push이다.

스택을 완성한 뒤, for문과 get() 메소드를 이용해 스택 내부 모든 원소들의 합을 구해 출력한다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
		Stack<Integer> stack=new Stack<>();
		
		int K=Integer.parseInt(in.readLine());
		for(int i=0; i<K; i++) {
			int input=Integer.parseInt(in.readLine());
			if(input==0)
				stack.pop();
			else
				stack.push(input);	
		}
		
		int sum=0;
		for(int i=0; i<stack.size(); i++) {
			sum+=stack.get(i);
		}
		
		System.out.println(sum);
	}
}

'백준' 카테고리의 다른 글

백준 10845: 큐(java)  (0) 2024.07.14
백준 4949: 균형잡힌 세상(java)  (0) 2024.07.12
백준 28278: 스택 2(java)  (0) 2024.07.12
백준 9012: 괄호(java)  (0) 2024.07.12
백준 10828: 스택(java)  (0) 2024.07.12