SW 공부노트

[백준/자바] 10773번: 제로 본문

백준풀이

[백준/자바] 10773번: 제로

요빈 2023. 5. 17. 11:56

https://www.acmicpc.net/problem/10773

 

10773번: 제로

첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000) 이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경

www.acmicpc.net


스택을 이용하면 쉽게 구현할 수 있는 문제이다.

자바에서 스택을 사용할 수 있는 방법은 두 가지가 있다.

 

  • 직접 구현
  • Util 패키지 Stack 클래스

 

1. 직접 구현

 

스택을 직접 구현할 땐 데이터를 담을 배열(stk)마지막 원소 위치를 가리키는 변수(ptr)을 사용하면 된다.

import java.io.*;
import java.util.*;

public class Boj_10773 {

   public static void main(String[] args) throws NumberFormatException, IOException {
       // TODO Auto-generated method stub

       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       int K = Integer.parseInt(br.readLine());
       int[] stk = new int[K];
       int ptr = 0; int sum = 0;

       for(int i = 0; i<K; i++) {
           int n = Integer.parseInt(br.readLine());
           if(n != 0)
               stk[ptr++] = n;
           else
               ptr --;
       }

       for(int i = 0; i<ptr; i++) 
           sum += stk[i];

       System.out.println(sum);
   }
}

 

2. 스택 클래스 이용

 

스택 클래스를 이용해 경우에 맞게 pop(), push()를 사용한다.

import java.io.*;
import java.util.*;

public class Boj_10773 {

   public static void main(String[] args) throws NumberFormatException, IOException {
       // TODO Auto-generated method stub
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       int K = Integer.parseInt(br.readLine());
       Stack<Integer> stk = new Stack<>();

       for(int i = 0; i<K; i++) {
           int n = Integer.parseInt(br.readLine());
           if(n != 0)
               stk.push(n); // stk.add(n)도 가능
           else
               stk.pop();
       }

       int sum = 0;
       for(int i : stk) 
           sum += i;

       System.out.println(sum);
   }
}