Link to the original text: he Xiaodong’s blog
Efficient perfect square number
Give a positive integernum
Write a function ifnum
Is a complete squareTrue
, otherwise returnFalse
。
Note: do not use any built-in library functions, such assqrt
。
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
Source: leetcode
Links: valid perfect squares
Solution 1
PHP cannot be usedpow
Function, the operation is** 0.5
In this way, self multiplying 0.5 times fromPhp5.6.0 startThe effect is the same as root.
code
class Solution {
/**
* @param Integer $num
* @return Boolean
*/
function isPerfectSquare($num) {
return $num**0.5 == (int)($num**0.5);
}
}
Solution 2
By using the properties of complete square numbers,A perfect square is the sum of a series of odd numbersFor example:
1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+(2n-1) = (2n-1 + 1) n/2 = n* n
The time complexity is O (sqrt (n)).
code
class Solution {
/**
* @param Integer $num
* @return Boolean
*/
function isPerfectSquare($num) {
$start = 1;
while($num > 0)
{
$num - = $start; // decrements to 0
$start + = 2; // each time + 2 remains a continuous odd number
}
return $num == 0;
}
}
Solution 3
Binary search
code
class Solution {
/**
* @param Integer $num
* @return Boolean
*/
function isPerfectSquare($num) {
$left = 0;
$right = $num;
while($left < $right)
{
$mid = $right - floor(($right-$left)/2);
if ($mid * $mid == $num) {
return true;
} elseif ($mid * $mid > $num) {
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
return $left * $left == $num;
}
}
Reference link: Square
Pass by recommendation algorithm