CountingBits   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 14
eloc 31
c 2
b 0
f 0
dl 0
loc 59
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A countBits() 0 11 3
A countBits2() 0 12 4
A countBits4() 0 11 3
A countBits3() 0 17 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class CountingBits
8
{
9
    public static function countBits(int $num): array
10
    {
11
        if ($num <= 0) {
12
            return [];
13
        }
14
        $bits = array_fill(0, $num + 1, 0);
15
        for ($i = 1; $i <= $num; $i++) {
16
            $bits[$i] = $bits[$i & ($i - 1)] + 1;
17
        }
18
19
        return $bits;
20
    }
21
22
    public static function countBits2(int $num): array
23
    {
24
        if ($num <= 0) {
25
            return [];
26
        }
27
        $bits = array_fill(0, $num + 1, 0);
28
        $bits[0] = 0;
29
        for ($i = 1; $i <= $num; $i++) {
30
            $bits[$i] = ($i & 1) === 0 ? $bits[$i >> 1] : $bits[$i - 1] + 1;
31
        }
32
33
        return $bits;
34
    }
35
36
    public static function countBits3(int $num): array
37
    {
38
        if ($num <= 0) {
39
            return [];
40
        }
41
        $bits = array_fill(0, $num + 1, 0);
42
        $bits[0] = 0;
43
        $pow = 1;
44
        for ($i = 1, $t = 0; $i <= $num; $i++, $t++) {
45
            if ($i === $pow) {
46
                $pow *= 2;
47
                $t = 0;
48
            }
49
            $bits[$i] = $bits[$t] + 1;
50
        }
51
52
        return $bits;
53
    }
54
55
    public static function countBits4(int $num): array
56
    {
57
        if ($num <= 0) {
58
            return [];
59
        }
60
        $bits = array_fill(0, $num + 1, 0);
61
        for ($i = 1; $i <= $num; $i++) {
62
            $bits[$i] = $bits[$i / 2] + $i % 2;
63
        }
64
65
        return $bits;
66
    }
67
}
68