알고리즘/코테

[백준 1019] 책 페이지

kiwiiiv 2022. 4. 4. 22:25

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

 

1019번: 책 페이지

첫째 줄에 0이 총 몇 번 나오는지, 1이 총 몇 번 나오는지, ..., 9가 총 몇 번 나오는지를 공백으로 구분해 출력한다.

www.acmicpc.net

 

횟수를 세는 규칙을 찾는 문제

 

0~9 페이지 묶음은 각 숫자가 1개씩 나온 묶음이다.

10~19 묶음에서 1의 자리 숫자들의 횟수는 1개씩으로 동일하지만, 10의자리 수 1은 그렇지 않다.

 

이를 이용하여 x0~x9 페이지로 묶어 각 자릿수(1의자리, 10의자리, 100의자리,,)마다 횟수를 카운트하기로 함.

먼저 첫 페이지를 x0으로, 마지막 페이지를 x9로 만들기 위하여 페이지를 조정한 후,

페이지 묶음에 대하여 수를 카운트하였다

 

 

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

class Main {
    static double[] count = new double[10];

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        int start = 1;
        int end = N;
        int digit = 1;
        while (start <= end) {
            //페이지 조정
            while (start % 10 != 0 && start <= end) {
                addCount(start, digit);
                start++;
            }

            while (end % 10 != 9 && start <= end) {
                addCount(end, digit);
                end--;
            }

            if (start > end) break;


            start /= 10;
            end /= 10;

            addCountByRange(0, 10, (end - start + 1) * digit);
            digit *= 10;
        }

        for (int i = 0; i < 10; i++) {
            System.out.printf("%.0f ", count[i]);
        }


    }

    private static void addCountByRange(int startIndex, int endIndex, double dCount) {
        for (int i = startIndex; i < endIndex; i++) {
            count[i] += dCount;
        }
    }

    private static void addCount(int number, double digit) {
        while (number > 0) {
            count[number % 10]+=digit;
            number /= 10;
        }
    }
}