[프로그래머스_ Java_Lv0] 제곱근 판별하기, 약수 구하기

박경희·2024년 1월 31일

코딩테스트

목록 보기
33/69

public static int solution(int n) {
        int sqrt = (int) Math.sqrt(n);
        if (sqrt * sqrt == n) {
            return 1;
        } else {
            return 2;
        }
    }
  • Math.sqrt(n)으로 제곱근 구하고

  • int로 형변환한 뒤 다시 제곱해서 n과 같으면 제곱수


Math.sqrt(n)

√n, 즉 n의 제곱근을 double 타입으로 반환


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

        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                list.add(i);
            }
        }
        return list.stream().mapToInt(i -> i).toArray();
    }

0개의 댓글