어떤 자연수를 제곱했을 때 나오는 정수를 제곱수라고 합니다. 정수 n이 매개변수로 주어질 때, n이 제곱수라면 1을 아니라면 2를 return하도록 solution 함수를 완성해주세요.
function solution(n) {
return Math.pow(Math.floor(Math.sqrt(n)), 2) === n ? 1 : 2;
}
Math.sqrt로 제곱근(루트)를 구하고 Math.floor로 내림을 한 뒤 다시 제곱하여 주어진 값과 일치하는 지 비교했습니다.
function solution(n) {
return Number.isInteger(Math.sqrt(n)) ? 1 : 2;
}
Number.isInteger인수의 값이 정수인지 아닌지를 반환하는 메서드입니다. 이걸로 더 간편하게 코드를 짤 수 있었습니다.