Test Failed
Push — master ( 9d5dfe...c535e5 )
by Jinyun
19:23
created

ValidPerfectSquare::isPerfectSquare()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 18
rs 9.5555
cc 5
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ValidPerfectSquare
8
{
9
    public static function isPerfectSquare(int $num): bool
10
    {
11
        if ($num <= 0) {
12
            return false;
13
        }
14
        [$low, $high] = [0, intdiv($num + 1, 2)];
15
        while ($low <= $high) {
16
            $mid = $low + intdiv($high - $low, 2);
17
            if ($mid * $mid > $num) {
18
                $high = $mid - 1;
19
            } elseif ($mid * $mid < $num) {
20
                $low = $mid + 1;
21
            } else {
22
                return true;
23
            }
24
        }
25
26
        return false;
27
    }
28
29
    public static function isPerfectSquare2(int $num): bool
30
    {
31
        if ($num <= 0) {
32
            return false;
33
        }
34
        $i = $n = 1;
35
        while ($n < $num) {
36
            $i++;
37
            $n = $i * $i;
38
        }
39
40
        return $n === $num;
41
    }
42
}
43