https://school.programmers.co.kr/learn/courses/30/lessons/120897
정수 n
이 매개변수로 주어질 때, n
의 약수를 오름차순으로 담은 배열을 return하도록 solution 함수를 완성해주세요.
1 ≤ n ≤ 10,000
n | result |
---|---|
24 | [1, 2, 3, 4, 6, 8, 12, 24] |
29 | [1, 29] |
24의 약수를 오름차순으로 담은 배열 [1, 2, 3, 4, 6, 8, 12, 24]를 return합니다.
29의 약수를 오름차순으로 담은 배열 [1, 29]를 return합니다.
class Solution {
public int[] solution(int n) {
int[] divisor=new int[10000];
int count=0;
int i=1;
while(n>=i){
if(n%i==0){//약수
divisor[count]=i;
count++;
}
i=i+1;
}
int[] answer = new int[count];
for(int j=0;j<count;j++){
answer[j]=divisor[j];
}
return answer;
}
}
i
수를 1부터 1씩 증가시키면서 정수 n
이랑 나머지 계산을 했다.
나머지가 0이면 약수이다.