1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | class HappyNumber |
||
8 | { |
||
9 | public static function isHappy(int $n): bool |
||
10 | { |
||
11 | if ($n <= 0) { |
||
12 | return false; |
||
13 | } |
||
14 | $helper = static function (int $num) { |
||
15 | [$sum, $tmp] = [0, null]; |
||
16 | while ($num) { |
||
17 | $tmp = $num % 10; |
||
18 | $sum += $tmp * $tmp; |
||
19 | $num /= 10; |
||
20 | } |
||
21 | return $sum; |
||
22 | }; |
||
23 | |||
24 | $slow = $fast = $n; |
||
25 | do { |
||
26 | $slow = $helper($slow); |
||
27 | $fast = $helper($fast); |
||
28 | $fast = $helper($fast); |
||
29 | } while ($slow !== $fast); |
||
30 | |||
31 | return $slow === 1; |
||
32 | } |
||
33 | |||
34 | public static function isHappy2(int $n): bool |
||
35 | { |
||
36 | if ($n <= 0) { |
||
37 | return false; |
||
38 | } |
||
39 | $visited = []; |
||
40 | while ($n !== 1 && ! in_array($n, $visited, true)) { |
||
41 | array_push($visited, $n); |
||
42 | $n = array_sum(array_map(fn ($x) => $x ** 2, str_split((string) $n))); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
43 | } |
||
44 | |||
45 | return !in_array($n, $visited, true); |
||
46 | } |
||
47 | } |
||
48 |