본문 바로가기
프로그래머스 문제풀이

프로그래머스 Level 1 : 나누어 떨어지는 숫자 배열

by 공부합시다홍아 2020. 6. 29.

using System;
using System.Collections.Generic;

public class Solution {
    public int[] solution(int[] arr, int divisor) {
        int[] answer = new int[]{ };
        int cnt = 0; //카운트 지정
        List<int> list = new List<int>();   //사이즈 지정 없이 값을 추가 가능 
        for (int i = 0; i < arr.Length; i++) //배열의 길이만큼 반복
        {
            if (arr[i] % divisor == 0) //인덱스 i를 divisor로 나누어 떨어질 때
            {
                list.Add(arr[i]); //i를 추가한다.
                cnt++; // 카운트 1증가
            }
        }
        if (cnt == 0) // 카운트가 0이라면 (증가하지 않았다면 = 나누어 떨어지는 값이 없다면 )
        {
            list.Add(-1); // -1를 추가
        }
        answer = list.ToArray();  //list를 배열로 바꿔준다.
        Array.Sort(answer);  // answer 을 정렬시킨다
        return answer;
    }
}

728x90