Test Failed
Push — master ( a6ce87...541811 )
by Jinyun
02:21
created

HappyNumber::isHappy()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 23
rs 9.7333
cc 4
nc 2
nop 1
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
It seems like str_split((string)$n) can also be of type true; however, parameter $array of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

42
            $n = array_sum(array_map(fn ($x) => $x ** 2, /** @scrutinizer ignore-type */ str_split((string) $n)));
Loading history...
43
        }
44
45
        return !in_array($n, $visited, true);
46
    }
47
}
48