알고리즘

백준 1052번 물병 (JAVA)

박카스마시며코딩 2023. 9. 24. 17:22

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

 

1052번: 물병

지민이는 N개의 물병을 가지고 있다. 각 물병에는 물을 무한대로 부을 수 있다. 처음에 모든 물병에는 물이 1리터씩 들어있다. 지민이는 이 물병을 또 다른 장소로 옮기려고 한다. 지민이는 한 번

www.acmicpc.net

 

저는 이진법을 통해 문제를 해결하였습니다.

먼저 n을 이진법으로 표현하고 1의 개수를 찾습니다. 이 1의 개수가 k보다 작다면 바로 0을 리턴합니다.

k보다 크다면 이 1의 개수를 줄여나가도록 하였습니다. 그래서 이진법에서 낮은 1부터 없어지도록 해당 자리 수의 이진수 1에 해당하는 값을 추가하여 문제를 해결하였습니다.

 

package BOJ.etc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_1052 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int k = stoi.apply(st.nextToken());
        String str = Integer.toBinaryString(n);
        int result = cal(str,k);
        System.out.println(result);
    }

    private static int cal(String str, int k) {
        int oneCnt = countOne(str);
        int result = 0;
        int index = str.length()-1;
        int num = 1;
        StringBuilder sb = new StringBuilder(str);
        while(oneCnt > k && index > 0){
            char ch = sb.charAt(index);
            if(ch != ONE){
                num *= 2;
                index--;
                continue;
            }
            result += num;
            while(ch == ONE && index > 0){
                sb.setCharAt(index,'0');
                oneCnt--;
                index--;
                ch = sb.charAt(index);
                num *= 2;
            }
            sb.setCharAt(index,ONE);
//            System.out.println(sb+" "+index+" "+result);
            oneCnt++;
        }
        return result;
    }
    private static final char ONE = '1';
    private static int countOne(String str) {
        int cnt = 0;
        for(int i = 0 ; i < str.length() ; i++){
            if(str.charAt(i) == ONE){
                cnt++;
            }
        }
        return cnt;
    }
}