코딩테스트/Programmers

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

grove1212 2025. 2. 20. 10:30

 

1. 내 풀이

String 으로 바꿨다가 Long으로 바꿨다가 살짝 온몸비틀기해서 풀었다.

 

class Solution {
    public Long solution(long n) {
        long answer = 0;
        double num = Math.sqrt(n);
        if(num - (int)num > 0) return -1L;
        
        String s = ((int)Math.sqrt(n) + 1) + "";
        Long num3 = Long.parseLong(s);
        return num3 * num3;
    }
}

 

 

2. 다른분 풀이

Math.pow와 Math.sqrt를 이용하여 간단히 구할 수 있었다.

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