백준 #31663번 Mean Words

jhj·2024년 5월 19일

백준 JAVA

목록 보기
474/583

푸는데 조금 어려움이 있었던 문제입니다.
처음에는 자릿수가 없으면 즉, null이면 아스키 숫자를 더해주는 total에 0을 더해주면 될 것이라고 생각했습니다.
따라서 처음에 짰던 코드는 다음과 같습니다.

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		String[] a = new String[n];
		int max = 0;
		
		for(int i = 0; i < n; i++) {
			a[i] = sc.next();
			max = Math.max(max, a[i].length());
		}
		
		for(int i = 0; i < max; i++) {
			int total = 0;
			for(int j = 0; j < n; j++) {
				if(a[j].charAt(i) == '\0') {
                	total += 0;
                }else{
                	total += a[j].charAt(i);
                }
			}
			total = total / n;
			System.out.print((char)total);
		}
		sc.close();
	}
}

이렇게 코드를 짜니, 자릿수가 같은 수들만 넣으면 잘 돌아갔으나, 자릿수가 다른 단어들을 넣으면 오류가 나서 잘 돌아가지 않는 것을 확인 할 수 있었습니다.
아무래도 자릿수의 문제인 것 같아 코드를 수정하였고, 수정한 코드는 다음과 같았습니다.


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		String[] a = new String[n];
		int max = 0;
		
		for(int i = 0; i < n; i++) {
			a[i] = sc.next();
			max = Math.max(max, a[i].length());
		}
        
        for(int i = 0; i < n; i++) {
			if(a[i].length() < max) {
				for(int j = a[i].length(); j < max; j++) {
					a[i] += '0';
				}
			}
		}
		
		for(int i = 0; i < max; i++) {
			int total = 0;
			for(int j = 0; j < n; j++) {
				if(a[j].charAt(i) == '0') {
                	total += 0;
                }else{
                	total += a[j].charAt(i);
                }
			}
			total = total / n;
			System.out.print((char)total);
		}
		sc.close();
	}
}

맨 처음에 단어를 입력 받을 때, 주어진 단어들 중 가장 긴 단어의 자리 수를 구합니다. 그 후, 그 보다 짧은 단어의 문자들에 '0'을 추가 해 주었습니다.

그 후, a[j].charAt(i) == '0'일 때, 아스키 코드 값을 더해 주는 total에 0을 더해주도록 코드를 수정했습니다.

위 코드를 돌리니 이제 오류가 나서 코드가 안 돌아가지는 않았습니다. 그런데, 제가 예상했던 결과와는 다른 값을 얻게 되었습니다. 이를 살펴보니, total을 단순히 n으로 나누는 것이 아니라, 자릿수가 있는 단어들의 개수를 세서 그 개수로 나누어야 한다는 것을 알게 되었습니다.

그렇게 최종적으로 코드를 수정하였고, 수정한 코드는 다음과 같습니다.


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		String[] a = new String[n];
		int max = 0;
		
		for(int i = 0; i < n; i++) {
			a[i] = sc.next();
			max = Math.max(max, a[i].length());
		}
		
		for(int i = 0; i < n; i++) {
			if(a[i].length() < max) {
				for(int j = a[i].length(); j < max; j++) {
					a[i] += '0';
				}
			}
		}
		
		for(int i = 0; i < max; i++) {
			int total = 0;
			int count = 0;
			for(int j = 0; j < n; j++) {
				if(a[j].charAt(i) == '0') {
					total += 0;
					count++;
				}else {
					total += a[j].charAt(i);
				}
			}
			total = total / (n - count);
			System.out.print((char)total);
		}
		sc.close();
	}
}

짧은 단어들의 개수를 count로 센 후, total을 전체 단어의 개수 n개에서 count를 빼 주어 나누어 출력하도록 수정하였습니다.

profile
개발자를 꿈꾸는

0개의 댓글