임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
class Solution {
public long solution(long n) {
long answer;
double d = Math.sqrt(n);
long l = (long)d;
return answer = (d==l) ? (l+1)*(l+1) : -1;
}
}
습관적으로 if문을 사용하려다 드디어 삼항연산자를 이용해 코드를 풀었다. 🥳
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;
}
}
Math.pow((int)Math.sqrt(n), 2) == n → int형으로 변환한 n의 제곱이 n과 같다면
return (long) Math.pow(Math.sqrt(n) + 1, 2) → n+1의 제곱을 리턴
https://school.programmers.co.kr/learn/courses/30/lessons/12934