백준 - JAVA/스택
[백준] 10773번 제로 _ JAVA ( 주석 설명 )
wch_s
2023. 3. 10. 02:46
풀이
- stack 에 대한 기본적인 이해, push·pop 연산 이용
코드
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 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 num = Integer.parseInt(br.readLine());
if(num!=0)
stack.push(num);
else //0이면 가장 최근에 쓴 수를 지운다.
stack.pop();
}
int sum = 0;
//스택이 빌 때까지
while(!stack.empty()){
int num = stack.pop();
sum += num;
}
System.out.println(sum); //최종적으로 적어낸 수의 합 출력
}
}