Skip to content

Commit c535e52

Browse files
author
pony
committed
Add valid-perfect-square solution
1 parent 9d5dfe7 commit c535e52

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/leetcode/ValidPerfectSquare.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use leetcode\ValidPerfectSquare;
9+
10+
class ValidPerfectSquareTest extends TestCase
11+
{
12+
public function testIsPerfectSquare(): void
13+
{
14+
self::assertTrue(ValidPerfectSquare::isPerfectSquare(16));
15+
self::assertFalse(ValidPerfectSquare::isPerfectSquare(14));
16+
}
17+
18+
public function testIsPerfectSquare2(): void
19+
{
20+
self::assertTrue(ValidPerfectSquare::isPerfectSquare2(16));
21+
self::assertFalse(ValidPerfectSquare::isPerfectSquare2(14));
22+
}
23+
}

0 commit comments

Comments
 (0)