[프로그래머스] 정수 제곱근 판별- Java

선예원·2021년 10월 15일
0
post-thumbnail

문제 설명

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

풀이

class Solution {
    public long solution(long n) {
        long answer = n;
        
        if(Math.sqrt(n) % 1 == 0)
            answer = (long)((Math.sqrt(n)+1)*(Math.sqrt(n)+1));
        else
            answer = -1;
        return answer;
    }
}

다른 사람의 풀이

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;
  }
}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN