判断一个数字是否是平方数


DESCRIPTION

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
2
3
4
5
6
-1  =>  false
0 => true
3 => false
4 => true
25 => true
26 => false

SOLUTION

  • 方法一:
1
2
3
4
5
6
var isSquare = function (n) {
// 求平方根并取整
let roundSqrt = Math.round(Math.sqrt(n));
// 判断平方根相乘的结果是否与传入的数值相等
return n === roundSqrt * roundSqrt;
};
  • 方法二:
1
2
3
function isSquare(n) {
return Math.sqrt(n) % 1 === 0;
}

Reference

You’re a square!