-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHappyNumber.php
47 lines (40 loc) · 1.03 KB
/
HappyNumber.php
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
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace leetcode;
class HappyNumber
{
public static function isHappy(int $n): bool
{
if ($n <= 0) {
return false;
}
$helper = static function (int $num) {
[$sum, $tmp] = [0, null];
while ($num) {
$tmp = $num % 10;
$sum += $tmp * $tmp;
$num /= 10;
}
return $sum;
};
$slow = $fast = $n;
do {
$slow = $helper($slow);
$fast = $helper($fast);
$fast = $helper($fast);
} while ($slow !== $fast);
return $slow === 1;
}
public static function isHappy2(int $n): bool
{
if ($n <= 0) {
return false;
}
$visited = [];
while ($n !== 1 && ! in_array($n, $visited, true)) {
array_push($visited, $n);
$n = array_sum(array_map(fn ($x) => $x ** 2, str_split((string) $n)));
}
return !in_array($n, $visited, true);
}
}