본문 바로가기
Development/Baekjoon

[C#] 3052번: 나머지

by Mobics 2025. 8. 3.

 

목차


    백준 단계별로 풀어보기

    25.08.03

    4단계: 1차원 배열


    3052번: 나머지

    문제 링크 : https://www.acmicpc.net/problem/3052

     

    문제를 풀기 위해 알아야 할 개념

    - 배열을 처음 선언하고 따로 초기화를 해주지 않으면 모든 값이 '0'으로 초기화된다. --> 나머지가 0이라면 초기화된 값과 같아져서 답이 다르게 나온다.

     

    ※ 배열을 선언함과 동시에 모든 값을 초기화하는 방법

    - LINQ의 Enumerable.Repeat 메서드 사용

    • 장점 : 간결하며, LINQ를 활용하여 다양한 초기화 패턴을 만들 수 있다.
    • 단점 : LINQ를 사용하기 때문에 'using System.Linq;' 구문이 필요하다.
    using System.Linq;
    
    // Enumerable.Repeat(초기화값, 배열크기).ToArray();
    int[] arr = Enumerable.Repeat(-1, 10).ToArray();

     

    - Array.Fill 메서드 사용

    • 장점 : 간단하고 직관적이다.
    • 단점 : C# 4.5 이상 버전에서만 사용 가능하다.
    int[] arr = new int[10]
    // Array.Fill(배열 이름, 초기화값)
    Array.Fill(arr, -1);

     

    정답 코드

    class Backjoon
    {
        static void Main(string[] args)
        {
            int[] remainders = new int[10];
            int count = 10;
            for (int i = 0; i < 10; i++)
            {
                remainders[i] = -1;
            }
    
            for (int i = 0; i < 10; i++)
                {
                    string input = Console.ReadLine();
                    int number = int.Parse(input);
                    remainders[i] = number % 42;
                    for (int j = 0; j < 10; j++)
                    {
                        if (i == j) continue;
                        if (remainders[i] == remainders[j])
                        {
                            count--;
                            break;
                        }
                    }
                }
            Console.Write(count);
        }
    }

     

    'Development > Baekjoon' 카테고리의 다른 글

    [C#] 27866번: 문자와 문자열  (1) 2025.08.04
    [C#] 1546번: 평균  (2) 2025.08.04
    [C#] 10811번: 바구니 뒤집기  (0) 2025.08.04
    [C#] 10951번: A+B - 4  (0) 2025.07.23
    [C#] 15552번: 빠른 A+B  (1) 2025.07.18