본문 바로가기

프로그래머스

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

내 코드

class Solution {
public long solution(long n) {
long answer = -1;
double sqrt = Math.sqrt(n);

for (int i = 1; i <= sqrt; i++) {
if (Math.pow(i, 2) == n) {
answer = (long) Math.pow(i + 1, 2);
}
}
return answer;
}
}


다른 사람 코드 - 반복문이 필요가 없었다.

내가 푼 위 코드에서도 결국 i = sqrt일 때만 유효한 검사였다.

class Solution {
public long solution(long n) {
long answer = -1;

long sqrt = (long) Math.sqrt(n);

if (Math.pow(sqrt, 2) == n) {
answer = (long) Math.pow(sqrt + 1, 2);
}
return answer;
}
}