본문 바로가기
Algorithm/Baekjoon

[백준] 2577번 : 숫자의 개수 - Java

by unknownomad 2022. 3. 3.

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

 

2577번: 숫자의 개수

첫째 줄에 A, 둘째 줄에 B, 셋째 줄에 C가 주어진다. A, B, C는 모두 100보다 크거나 같고, 1,000보다 작은 자연수이다.

www.acmicpc.net



풀이

1. Scanner

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int value = (in.nextInt() * in.nextInt() * in.nextInt());
        String str = Integer.toString(value); //int ➡ String 형변환
        in.close();
		
        for (int i = 0; i < 10; i++) { //0~9 까지 검사할 반복문
            int cnt = 0; //카운팅할 변수
            for (int j = 0; j < str.length(); j++) {
                if ((str.charAt(j) - '0') == i) { //<str.charAt(j) - 48>과 동일
                    cnt++; //str의 숫자와 i가 일치할 때 +1
                }
            }
            System.out.println(cnt);
        }
    }
}

 

2. BufferedReader

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[] arr = new int[10];
        int val = Integer.parseInt(br.readLine())
                    * Integer.parseInt(br.readLine())
                    * Integer.parseInt(br.readLine());
        String str = String.valueOf(val);
 
        for (int i = 0; i < str.length(); i++) {
            //배열 arr의 <str.charAt(i) - 48>번째 값에 +1
            arr[(str.charAt(i) - 48)]++;
        }
 
        for (int result : arr) {
            System.out.println(result);
        }
    }
}

 

3. BufferedReader + 나눗셈

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 val = Integer.parseInt(br.readLine()) 
                    * Integer.parseInt(br.readLine())
                    * Integer.parseInt(br.readLine());
        int[] arr = new int[10];
		
        while(val != 0) {
            //배열 arr의 <val % 10>번째에 +1
            arr[val % 10]++;
            //val 값을 한 자리씩 지우기
            val /= 10;
        }
		
        for(int result : arr) {
            System.out.println(result);
        }
    }
}

성능

  • BufferedReader > Scanner

 


출처 : https://st-lab.tistory.com/45

댓글