minghxx.blog
  • [프로그래머스 / 자바] 정수 제곱근 판별
    2023년 11월 24일 17시 13분 42초에 업로드 된 글입니다.
    작성자: 민발자
    728x90

    문제

    임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
    n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.

     

    풀이

    class Solution {
        public long solution(long n) {
            long answer = 0;
            Double x = Math.sqrt(n);
            if(x == x.intValue()) {
                answer = (long)Math.pow(x + 1, 2);
            } else {
                answer = -1;
            }
            return answer;
        }
    }

    x를 int형으로 변경했을때 x랑 같으면 제곱근

     

    참고할만한 다른 사람 풀이

    class Solution {
      public long solution(long n) {
          if (Math.pow((int)Math.sqrt(n), 2) == n) {
                return (long) Math.pow(Math.sqrt(n) + 1, 2);
            }
    
            return -1;
      }
    }

    제곱근을 int형으로 변환하고 다시 제곱했을때 n과 같으면 제곱근이다..

     

    class Solution {
      public long solution(long n) {
    
        double i = Math.sqrt(n);
    
        return Math.floor(i) == i ? (long) Math.pow(i + 1, 2) : -1;
      }
    }

    n 제곱근 구하고 내림했을때 i랑 같으면 제곱근

    728x90
    댓글