본문 바로가기
알고리즘/Codewars

[Codewars] You're a square! (7 kyu) / JavaScript

by fluss 2022. 10. 10.

https://www.codewars.com/kata/54c27a33fb7da0db0100040e/javascript

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

A square of squares

You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!

However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a perfect square.

 

Task

Given an integral number, determine if it's a square number:

In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

The tests will always use some integral number, so don't worry about that in dynamic typed languages.

 

Examples

-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false​
 

정사각형의 정사각형

당신은 블록 쌓기를 좋아합니다. 특히 정사각형으로 블록을 쌓는 것을 좋아합니다. 그리고 당신이 더 좋아하는 것은 그것들을 정사각형으로 배열하는 것입니다!

그렇지만 때때로 그것들을 정사각형으로 배열할 수 없습니다. 대신 그것들은 평범한 사각형이 될 수 있습니다. 빌어먹을 것들! 만약 당신이 지금 헛된 일을 하고 있는지 알 수 있다면... 잠깐! 바로 그거예요! 당신은 쌓인 블록의 수가 완전 제곱수인지만 확인하면 됩니다.

과제

정수를 받으면, 그것이 제곱수인지 확인하세요:

수학에서 제곱수, 혹은 완전 제곱수는 정수의 제곱인 정수입니다; 다시 말해, 어떤 정수와 그 자신의 곱입니다.

테스트는 항상 정수를 사용하므로 동적 타이핑 언어에서 그것에 대해 걱정하지 마세요.

 

예시

-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false​

 

풀이

var isSquare = function(n){
  if(Number.isInteger(Math.sqrt(n))) return true;
  return false;
}

if문으로 조건을 따져서 반환 값을 결정했는데 Number.isInteger()이 매개변수의 값이 정수이면 true를 아니면 false를 반환하는 함수이기 때문에 if문을 쓰지 않고 바로 Number.isInteger(Math.sqrt(n))를 반환해주어도 된다.

 

다른 사람의 좋았던 풀이

function isSquare(n) {
  return Math.sqrt(n) % 1 === 0;
}

 

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt

 

Math.sqrt() - JavaScript | MDN

Math.sqrt() 함수는 숫자의 제곱근을 반환합니다.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

 

Number.isInteger() - JavaScript | MDN

**Number.isInteger() **메서드는 주어진 값이 정수인지 판별합니다.

developer.mozilla.org

 

댓글