본문 바로가기

코딩 테스트/백준

[백준 1019번 문제, JAVA] 책 페이지

728x90
반응형

문제

지민이는 전체 페이지의 수가 N인 책이 하나 있다. 첫 페이지는 1 페이지이고, 마지막 페이지는 N 페이지이다. 각 숫자가 전체 페이지 번호에서 모두 몇 번 나오는지 구해보자.


코드

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

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int a = 1;
        int b = Integer.parseInt(br.readLine());
        int[] counts = new int[10];
        int digit = 1;

        while(a <= b) {
            if (b % 10 != 9) {
                calc(b, counts,digit);
                b--;
            }
            if (b < a) {
                break;
            }
            if (a % 10 != 0) {
                calc(a, counts, digit);
                a++;
            }
            if (a % 10 == 0 && b % 10 == 9) {
                for (int i = 0; i < 10; i++) {
                    counts[i] += (b / 10 - a / 10 + 1) * digit;
                }
                digit *= 10;
                a /= 10;
                b /= 10;
            }
        }
        Arrays.stream(counts).forEach(i->System.out.print(i + " "));
    }

    public static void calc(int n, int[] counts, int digit) {
        while (n > 0) {
            counts[n % 10] += digit;
            n /= 10;
        }
    }
}

해결

정신건강에 해끼치는 것을 싫어하는 사람은 쳐다보지말자
 
 


참고

https://www.slideshare.net/Baekjoon/baekjoon-online-judge-1019

Baekjoon Online Judge 1019번 풀이

https://www.acmicpc.net/problem/1019 "책 페이지" 문제 풀이입니다.

www.slideshare.net

 
밑에 이거는 시간 초과나는 일일이 비교해서 카운팅하는 방법

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        long input = Long.parseLong(br.readLine());
        List<Long> counts = new ArrayList<>(Collections.nCopies(10, 0L));

        for (long i = 1; i <= input; i++) {
            String[] tokens = String.valueOf(i).split("");
            for (String token : tokens) {
                counts.set((int)Long.parseLong(token), counts.get((int)Long.parseLong(token)) + 1L);
            }
        }
        StringBuilder sb = new StringBuilder();
        counts.forEach(i -> sb.append(i).append(" "));
        System.out.println(sb);
    }
}

 
 

728x90
반응형