문제 풀이

[백준] 3052번: 나머지 - JAVA (자바)

auyeol 2023. 5. 12. 13:34
728x90

 

 

문제

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

 

3052번: 나머지

각 수를 42로 나눈 나머지는 39, 40, 41, 0, 1, 2, 40, 41, 0, 1이다. 서로 다른 값은 6개가 있다.

www.acmicpc.net

 

정수를 10번 입력받은 뒤, 42로 나누었을 때, 서로 다른 나머지가 몇 개 있는지 출력하는 문제이다.

 

 

입력                                    출력
42                                      1
84
252
420
840
126
42
84
420
126

 

 

------------------------------------------------------------------------------------------------------------------

 

풀이

1. 10개의 수를 입력받을 배열 array1[]의 크기를 10으로 설정해주었다.

 

2. 42로 나누었을 때 나머지는 0 ~ 41까지 존재하므로 배열의 크기를 42개로 설정하였다.   (int compare[] = new int[42])

   

3. 나머지 개수를 세어줄 변수 count와 입력받을 수 num을 0으로 초기화 해준 다음, Arrays.fill을 통해 배열 compare[]을 0으로 초기화 해주었다.

 

4. array1[]에 정수를 입력받은 뒤, 42로 나눈 나머지의 값을 compare[] 배열에 넣어주었다.

     > 나머지가 1인 경우에는 항상 1번째 배열에 저장, 2인 경우에는 2번째 배열 ......

     > 5번에서 0이 아닌 경우를 조건으로 주었기에 +1한 값을 num에 저장하게 하였다.

 

5. for문을 이용해서 compare[] 배열의 값이 0이 아닌 경우 count를 1씩 증가하게 하였다. 

 

6. count값 출력

 

(1) Scanner 사용 

 

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int array1[] = new int[10];
		int compare[] = new int[42];
		int count = 0, num = 0;
		
		Arrays.fill(compare, 0);
		
		for(int i=0;i<array1.length;i++) {
			array1[i] = sc.nextInt();
			num = array1[i] % 42; 
			
			compare[num] = num + 1;	
		}
		for(int i=0;i<compare.length;i++) {
			if(compare[i]!=0) count++;	
		}
		sc.close();
        
		System.out.println(count);
		
		
	}

}

 

 

------------------------------------------------------------------------------------------------------------------

 

(2) BufferdReader 사용 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int array1[] = new int[10];
		int compare[] = new int[42];
		int count = 0, num = 0;
		
		Arrays.fill(compare, 0);
		for(int i=0;i<array1.length;i++) {
			array1[i] = Integer.parseInt(br.readLine());
			num = array1[i] % 42; 
			
			compare[num] = num + 1;	
		}
		for(int i=0;i<compare.length;i++) {
			if(compare[i]!=0) count++;	
		}
		br.close();
		
		System.out.println(count);
		
	}

}

 

 

 

 

Scanner 사용

 

BufferdReader 사용

 

728x90