반응형
문제
임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
제한조건
- n은 1이상, 50000000000000 이하인 양의 정수입니다.
입출력 예
n | return |
---|---|
121 | 144 |
3 | -1 |
풀이
function integerSquareRoot(n) {
let answer = 0;
//if integer square root is an integer, return math pow
//if integer square root is not an integer, return -1
if (Math.sqrt(n) % 1 === 0) {
answer = Math.pow(Math.sqrt(n) + 1, 2);
} else {
answer = -1;
}
return answer;
}
export { integerSquareRoot };
import { integerSquareRoot } from "../src/integerSquareRoot";
describe("integerSquareRoot", () => {
it("should return the integer square root of a number", () => {
expect(integerSquareRoot(121)).toBe(144);
});
it("should return -1 if the number is not an integer square root", () => {
expect(integerSquareRoot(3)).toBe(-1);
});
});
출처
다른 풀이
function nextSqaure(n){
switch(n % Math.sqrt(n)){
case 0:
return Math.pow(Math.sqrt(n) + 1, 2);
default:
return "-1";
}
}
반응형
'IT > Javascript' 카테고리의 다른 글
문자열 내 마음대로 정렬하기 (0) | 2022.07.13 |
---|---|
최소직사각형 (0) | 2022.07.13 |
이상한문자 만들기 (0) | 2022.07.13 |
x만큼 간격이 있는 n개의 숫자 (0) | 2022.07.13 |
핸드폰 번호가리기 (0) | 2022.07.13 |
하샤드 수 (0) | 2022.07.13 |
문자열 다루기 (0) | 2022.07.13 |
최대공약수와 최소공배수 (0) | 2022.07.13 |