ALGORITHM/PROGRAMMERS

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

0298 2020. 12. 13. 13:24

programmers.co.kr/learn/courses/30/lessons/12934

 

코딩테스트 연습 - 정수 제곱근 판별

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

programmers.co.kr

2020-12-13


1
2
3
4
5
6
7
8
9
10
11
import java.math.BigDecimal;
 
public class Solution12934 {
    public static void main(String[] args) {
        long n = 121;
        BigDecimal dec = new BigDecimal(Math.sqrt(n));
        BigDecimal check = dec.movePointRight(0);
        if(check.scale() == 0System.out.println((long)Math.pow((Math.sqrt(n)+1), 2));
        else System.out.println("-1");
    }
}
cs

BigDecimal을 이용하여 풀었다.

 

BigDecimal에서 movePointRight를 이용하여, scale()이 0인 경우 제곱근이 존재하는 것이고 다른 숫자가 나오는 경우 제곱근이 존재하지 않는다고 판단했다.