Shiny Sky Blue Star

백준 문제 풀이/백준 (JAVA)

JAVA 백준 1094 막대기

gamja00 2024. 7. 7. 19:51

 

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


문제

  1. 길이가 64cm인 막대를 가지고 있음.
  2. 첫째 줄에 X (1 <= X <= 64) 입력.
  3. 주어진 막대기를 절반으로만 자르면서 Xcm가 되도록 만들 때의 붙여진 막대기의 개수 출력

 

 

최종 코드

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 X = Integer.parseInt(br.readLine());
        br.close();

        Stack<Integer> stack = new Stack<Integer>();
        int stick = 64;
        int count = 0;

        while(X!=0) {
            if(stick>X){
                stick/=2;
                if(stick<X){
                    stack.push(stick);
                }
            } else{
                X-=stick;
                if(!stack.isEmpty()){
                    stick=stack.pop();
                }
                count++;
            }
        }

        System.out.println(count);
    }
}