Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

KSI일기장

프로그래머스 소인수분해(자바) Arrays.copyOf() & stream().distinct() 본문

JavaAlgorithm

프로그래머스 소인수분해(자바) Arrays.copyOf() & stream().distinct()

MyDiaryYo 2024. 2. 1. 16:54

 

 

 

 

import java.util.Arrays;
class Solution {
    public int[] solution(int n) {
        int[] answer = {};
         int cnt = 0;

       for (int i = 2; i <= n; i++){ 
            while (n % i == 0){ //n을 i로 나눴을 때 나머지가 0인 경우(나머지 없이 나눠지는 경우)
                n /= i;     // == n = n / i; -> n을 i로 나눠 n에 대입  ex) n = 10 -> 5 = 10/2, 1 = 5/5
                cnt++;      //while 조건에 맞아 n /= i; 를 실행할 때 마다 cnt +1 증가
                answer = Arrays.copyOf(answer, cnt); //배열 answer에 현재 answer를 길이가 cnt로 확장
                                                    //->answer초기길이가 0이므로 i를 answer에 저장하기 위해서 cnt만큼 길이를 늘려야하기 때문에 수행
                answer[cnt - 1] = i;  //answer 인덱스(cnt(배열길이) - 1)에 n을 나눈 i값을 추가
            }
        }

        answer = Arrays.stream(answer).distinct().toArray(); //stream.distinct를 이용한 배열 answer의 충복값 제거
                                                            // toArray()를 하지 않으면 결과가 stream형태여서 배열인 answer에 담을 수 없다.
                                                            
        return answer;
    }
}

 

 

Arrays.copyOf(복사할 배열 변수명, 배열의길이(int) );