알고리즘 공부/백준 문제풀이

[백준] 3052 : 나머지 (JAVA)

송테이토 2022. 10. 6. 20:32

백준 3052 자바

 

나머지

문제

두 자연수 A와 B가 있을 때, A%B는 A를 B로 나눈 나머지 이다. 예를 들어, 7, 14, 27, 38을 3으로 나눈 나머지는 1, 2, 0, 2이다.

수 10개를 입력받은 뒤, 이를 42로 나눈 나머지를 구한다. 그 다음 서로 다른 값이 몇 개 있는지 출력하는 프로그램을 작성하시오.

입력

첫째 줄부터 열번째 줄 까지 숫자가 한 줄에 하나씩 주어진다. 이 숫자는 1,000보다 작거나 같고, 음이 아닌 정수이다.

출력

첫째 줄에, 42로 나누었을 때, 서로 다른 나머지가 몇 개 있는지 출력한다.

예제 입력 1

1
2
3
4
5
6
7
8
9
10

예제 출력 1

10

각 수를 42로 나눈 나머지는 1, 2, 3, 4, 5, 6, 7, 8, 9, 10이다.

예제 입력 2

42
84
252
420
840
126
42
84
420
126

예제 출력 2

1

시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율

1 초 128 MB 137834 79679 67112 57.999%

1. HashSet으로 풀기

package Day1002;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class B3052 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int[] arr = new int[10];

		// 입력값에 42를 나눈 나머지를 배열에 재정렬
		for (int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextInt() % 42;
		}
		sc.close();

		// HashSet 생성
		Set<Integer> set = new HashSet<Integer>();
		for (int i : arr)
			set.add(i); // i에 arr 값을 하나씩 추가
		System.out.println(set.size()); //Hashset의 길이 구하기 size()

	}

}

HashSet 선언 방법

HashSet<Integer> set1 = new HashSet<Integer>();//HashSet생성
HashSet<Integer> set2 = new HashSet<>();//new에서 타입 파라미터 생략가능
HashSet<Integer> set3 = new HashSet<Integer>(set1);//set1의 모든 값을 가진 HashSet생성
HashSet<Integer> set4 = new HashSet<Integer>(10);//초기 용량(capacity)지정
HashSet<Integer> set5 = new HashSet<Integer>(10, 0.7f);//초기 capacity,load factor지정
HashSet<Integer> set6 = new HashSet<Integer>(Arrays.asList(1,2,3));//초기값 지정

Set 중복을 포함하지 않기 때문에, 문자열에서 중복을 제거한 것처럼 ***contains()***메소드를 사용하지 않더라도, 자동으로 중복이 제거가 됩니다.

Set에 기존의 int배열 값들을 전부 저장한 뒤, 정렬을 위해 ArrayList를 선언 하고 정렬한 후 출력하면 중복을 제거 한 후 정렬이 된 걸 볼 수 있습니다.

HashSet 값 추가

HashSet<Integer> set = new HashSet<Integer>();//HashSet생성
set.add(1); //값 추가
set.add(2);
set.add(3);

HashSet 값 삭제

HashSet<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));//HashSet생성
set.remove(1);//값 1 제거
set.clear();//모든 값 제거

HashSet 크기 구하기

HashSet<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));//HashSet생성

System.out.println(set.size());