백준 온라인 저지 문제풀이/JAVA
[baekjoon 2577번] 1차원 배열 - 숫자의 갯수
Good Program Good Programmer
2020. 12. 2. 10:47
문제
세 개의 자연수 A, B, C가 주어질 때 A×B×C를 계산한 결과에 0부터 9까지 각각의 숫자가 몇 번씩 쓰였는지를 구하는 프로그램을 작성하시오.
예를 들어 A = 150, B = 266, C = 427 이라면
A × B × C = 150 × 266 × 427 = 17037300 이 되고,
계산한 결과 17037300 에는 0이 3번, 1이 1번, 3이 2번, 7이 2번 쓰였다.
문제풀이
1. A*B*C의 자릿수를 구한다. 무조건 3자리 수만 입력되므로 자릿수는 7~9자리이다.
2. 배열을 선언한다.
3. 각 자릿수의 숫자에 해당 하는 번호의 배열을 1증가시키고 다음 자릿수로 넘어간다.
4. 배열을 출력한다.
소스코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int[] ABC = new int[3];
ABC[0] = Integer.parseInt(new StringTokenizer(br.readLine()).nextToken()); // A
ABC[1] = Integer.parseInt(new StringTokenizer(br.readLine()).nextToken()); // B
ABC[2] = Integer.parseInt(new StringTokenizer(br.readLine()).nextToken()); // C
int result = ABC[0]*ABC[1]*ABC[2];
int result_digits = 0;
// 100 < x < 1000 그러면 A*B*C는 무조건 7~9자리 숫자
// 1. A*B*C의 자릿수를 구한다.
for(int i = 9 ; i >= 7 ; i--) {
if(result/Math.pow(10,i-1) >= 1) {
result_digits = i;
break;
}
}
// 2. 배열을 선언한다.(자동으로 0으로 초기화 된다.)
int[] digits = new int[10];
// 3. result의 각 자릿수의 해당하는 배열의 번지를 1씩 증가시킨다.
for(int j = result_digits-1 ; j >= 0 ; j--) {
digits[(int)(result / Math.pow(10,j))]++;
result %= (int)Math.pow(10,j);
}
// 4. 배열을 출력한다.
for(int i: digits) {
bw.write(i+"\n");
}
bw.flush();
bw.close();
}
}
|
cs |
이 또한 숫자의 자릿수를 구하는 문제이다.