본문 바로가기
알고리즘 공부/백준

[JAVA 39일차 / 하루 3문제] 13909번, 28278번, 10773번

by maverick11471 2025. 3. 25.

1. 13909번 창문 닫기

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine()); // N 입력 받기
        System.out.println((int)Math.sqrt(N));  // N 이하의 완전제곱수 개수 출력
    }
}

2. 28278번 스택2

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        Stack<Integer> stack = new Stack<>();

        int N = Integer.parseInt(br.readLine()); // 명령 개수 입력

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int command = Integer.parseInt(st.nextToken());

            if (command == 1) { // push X
                int X = Integer.parseInt(st.nextToken());
                stack.push(X);
            } else if (command == 2) { // pop
                sb.append(stack.isEmpty() ? -1 : stack.pop()).append("\n");
            } else if (command == 3) { // size
                sb.append(stack.size()).append("\n");
            } else if (command == 4) { // empty
                sb.append(stack.isEmpty() ? 1 : 0).append("\n");
            } else if (command == 5) { // top
                sb.append(stack.isEmpty() ? -1 : stack.peek()).append("\n");
            }
        }

        System.out.print(sb.toString()); // 결과 출력
    }
}

3. 10773번 제로

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

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) {
                if (!stack.isEmpty()) {
                    stack.pop(); // 0이면 최근 값 제거
                }
            } else {
                stack.push(num); // 숫자 추가
            }
        }

        int sum = 0;
        while (!stack.isEmpty()) {
            sum += stack.pop(); // 남은 숫자들의 합 계산
        }

        System.out.println(sum); // 결과 출력
    }
}