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

나의 답안:
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
'오늘의 문제' 카테고리의 다른 글
| [백준 JAVA] 1546번 - 평균 (0) | 2022.05.27 |
|---|---|
| [백준 JAVA] 3052번 - 나머지 (0) | 2022.05.27 |
| [백준 JAVA] 2562번 - 최댓값 (0) | 2022.05.25 |
| [백준 JAVA] 10818번 - 최소, 최대 (0) | 2022.05.25 |
| [백준JAVA] 1110번 - 더하기 사이클 (0) | 2022.05.24 |