본문 바로가기
🫧 코테 : CodingTest

[프로그래머스] Java : 약수 구하기(copyOf)

by 예옹이 2024. 3. 20.

 

문제

정수 n이 매개변수로 주어질 때, n의 약수를 오름차순으로 담은 배열을 return하도록 solution 함수를 완성해주세요.

 

 

입출력 예

n result
24 [1, 2, 3, 4, 6, 8, 12, 24]
29 [1, 29]

 

 


 

 

 

Arrays.copyOf() 

: orginal 배열을 newLength만큼 복사하는 메서드

public static int[] copyOf(int[] original, int newLength)

 

 

  original 길이 > newLength

 

: original의 앞부터 newLength까지만 복사

 

  original 길이 < newLength

 

: 남는 뒷부분은 0 또는 null로 채워짐

 

 

 

 

 

코드

import java.util.*;

class Solution {
    public int[] solution(int n) {
        int[] answer = new int[n];
        int index = 0;
        
        for(int i=1; i<=n; i++){
            if(n%i == 0){
                answer[index] = i;
                index++;
            }
        }
        
        return Arrays.copyOf(answer, index);
    }
}

 

 

 

제가 작성한 코드는 여기서 확인하실 수 있습니다.

https://github.com/eonwy/programmers

 

GitHub - eonwy/programmers: 🔎 coding-test (programmers) 🔍

🔎 coding-test (programmers) 🔍. Contribute to eonwy/programmers development by creating an account on GitHub.

github.com