정수 제곱근 판별

2020.07.27

const isSqrt = (num) => {
  const sqrt = Math.sqrt(num);
  if (sqrt == Math.floor(sqrt)) {
    return true;
  }
  return false;
};

const solution = (n) => {
  if (isSqrt(n)) {
    return Math.pow(Math.sqrt(n) + 1, 2);
  }
  return -1;
};
  • 양의 정수의 제곱근인지 판별할 때 내가한 것처럼 Math.floor의 결과값과 비교할 수도 있고, parseInt의 결과값과 비교할 수도 있다.

  • Math.pow대신 **연산자를 쓰면 거듭제곱이 가능하다(es6스펙)

0개의 댓글