-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPerfectSquare.php
More file actions
41 lines (39 loc) · 945 Bytes
/
Copy pathValidPerfectSquare.php
File metadata and controls
41 lines (39 loc) · 945 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace App;
/**
* Valid Perfect Square
*
* Given a positive integer num, write a function which returns True if num is a perfect square else False.
* Follow up: Do not use any built-in library function such as sqrt.
*
* Example 1:
* Input: num = 16 Output: true
*
* Example 2:
* Input: num = 14 Output: false
*
* https://leetcode.com/problems/valid-perfect-square
*/
class ValidPerfectSquare
{
/**
* @param int $number
* @return bool
*/
public function isPerfectSquare(int $number): bool
{
$left = 1;
$right = $number;
while ($left <= $right) {
$mid = (int) (round($left + $right) / 2);
if ($mid * $mid > $number) {
$right = $mid - 1;
} elseif ($mid * $mid < $number) {
$left = $mid + 1;
} else {
return true;
}
}
return false;
}
}