프로그래머스 - 약수 구하기

박철현·2023년 5월 25일

프로그래머스

목록 보기
26/80

프로그래머스 - 약수 구하기

import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] solution(int n) {
        List<Integer> list = new ArrayList<>();

        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                if (!list.contains(i))
                    list.add(i);
                if (!list.contains(n / i))
                    list.add(n / i);
            }
        }

        return list.stream()
                .sorted()
                .mapToInt(a -> a.intValue())
                .toArray();
    }
}
  • 6x6 = 36의 경우 6이 두번 들어가므로, 위 두 조건을 동시에 검사하면 중복
profile
비슷한 어려움을 겪는 누군가에게 도움이 되길

0개의 댓글