Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 2577번 - 숫자의 개수 본문

오늘의 문제

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

jeongwon_ 2022. 5. 26. 13:53

 

나의 답안:

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));

		String str;
		int a = 0,b = 0,c = 0;
		int[] arr=new int[10];
		for(int i=0; i<3; i++) {	//세 값 입력 받기
			str=br.readLine();
			if(i==0) a=Integer.parseInt(str);
			if(i==1) b=Integer.parseInt(str);
			if(i==2) c=Integer.parseInt(str);
		}
		
		str=a*b*c+"";
		a=a*b*c;

		for(int i=0; i<str.length(); i++) {		// a*b*c값의 길이만큼 반복문
			arr[a%10]++;		//a*b*c%10 값을 배열의 index로 처리
			a=a/10;			//다음 자리의 나머지를 구하기 위해 10으로 나눈 값을 저장
		}
		
		for(int i=0; i<arr.length; i++)
			System.out.println(arr[i]);

	}
}

 

개선 답안 :

1)

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);  //valueOf()는 매개변수를 문자열로 반환해준다.
 
		for (int i = 0; i < str.length(); i++) {
			arr[(str.charAt(i) - 48)]++;  //** 아스키코드 0의 값은 48이다.
		}
 
		for (int v : arr) {	//향상 for문
			System.out.println(v);
		}
 
	}
}

 

2)

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) {		//**몫이 0이 아닐 때까지 반복
			arr[val%10]++;
			val/=10;
		}
		
		for(int result : arr) {
			System.out.println(result);
		}
	}
}

시간 상 별 차이가 없지만, 변수의 개수도 줄었고 보기에도 깔끔하다.  (답안과 역순)

 

개선 답안 출처: https://st-lab.tistory.com/45