본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.0

[프로그래머스 - JAVA] 소인수분해

by 코딩하는 흰둥이 2023. 3. 12.
반응형

 

  • 내 풀이
import java.util.ArrayList;
import java.util.Arrays;

class Solution {
    public int[] solution(int n) {
        int[] answer = {};
        
        int count = 2;
        ArrayList<Integer> check = new ArrayList<>();

        // 반복문을 통해서 매개변수를 2부터 계속 나누어준다.
        // 나머지가 나오지 않아야 하기 때문에 2부터 시작한다.
        while (n >= count){
            if (n % count == 0){
                check.add(count);
                n = n/count;
            }else {
                count++;
            }
        }

        // 소인수가 없다면 check에 담긴 값이 없기 때문에 answer를 매개변수 값으로 초기화 시켜준다. 
        if (check.isEmpty()){
            answer = new int[]{n};
        }else {
        // 중복된 값을 제거하기 위해 distinct()를 사용한다.
            answer = check.stream().distinct().mapToInt(v -> v).toArray();
        }
        
        return answer;
    }
}

어렵다...몇시간동안 머리를 싸매며, 검색해가며 굴리고 굴리다 풀어본다.

 

 

  • 다른 사람 풀이
import java.util.LinkedHashSet;

class Solution {
    public int[] solution(int n) {
        LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();

        int i = 2;
        while (n != 0 && i <= n) {
            if (n % i == 0) {
                primeNumbers.add(i);
                n /= i;
            } else {
                i++;
            }
        }

//        System.out.println(primeNumbers);

        return primeNumbers.stream().mapToInt(Integer::intValue).toArray();
    }
}

이 분 풀이를 보고 중복제거를 위한 Set이 생각났다...

평소에 Set을 잘 사용하지 않다보니 머리속에서 딱! 떠오르지가 않는다.

오늘 이렇게 고생했으니 다음번에는 좀 더 빨리 떠오르려나? 그래도 distinct 했으니까..!!

댓글