정수 제곱근 판별

Sheryl Yun·2023년 7월 4일
0

문제 링크🔗

풀이

정수인지 여부를 Math.floor 값과 비교해서 판단했다.

function solution(n) {
    let sqrtNum = Math.sqrt(n);
    
    if (sqrtNum === Math.floor(sqrtNum)) {
        return Math.pow((sqrtNum + 1), 2);
    } else return -1;
}

다른 풀이를 보니 자바스크립트의 Number.isInteger 메서드를 활용하고 있었다. === 비교 연산자가 없어서 더 가독성이 좋은 코드인 것 같다.

function solution(n) {
    let sqrtNum = Math.sqrt(n);
    
    if (Number.isInteger(sqrtNum)) {
        return Math.pow((sqrtNum + 1), 2);
    } else return -1;
}
profile
영어강사, 프론트엔드 개발자를 거쳐 데이터 분석가를 준비하고 있습니다 ─ 데이터분석 블로그: https://cherylog.tistory.com/

0개의 댓글