출처:https://programmers.co.kr/learn/courses/30/lessons/12934
임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
제한 사항
n은 1이상, 50000000000000 이하인 양의 정수입니다.
n | return |
---|---|
121 | 144 |
3 | -1 |
121은 양의 정수 11의 제곱이므로, (11+1)를 제곱한 144를 리턴합니다.
3은 양의 정수의 제곱이 아니므로, -1을 리턴합니다.
function solution(n) {
if(Number.isInteger(Math.sqrt(n))){
return (Math.sqrt(n)+1) * (Math.sqrt(n)+1)
}else {
return -1
}
}
삼항연산자사용하자 제발...
function solution(n) {
return Number.isInteger(Math.sqrt(n))?
(Math.sqrt(n)+1) * (Math.sqrt(n)+1) : -1}
한줄이면 끝날 걸 왜 맨날 늘어쓰는지..
Number.isInteger()/ Math.sqrt(n)은 자주 안써서 잘 기억해두어야 할 것 같다.
Number.isInteger():
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Math.sqrt(n):
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt