File tree 1 file changed +5
-22
lines changed
1 file changed +5
-22
lines changed Original file line number Diff line number Diff line change 1
1
//lint:file-ignore U1000 Ignore all unused code
2
2
package main
3
3
4
- // 2の冪乗の時はMSBのみが1になる
5
- // それ以外の場合はMSB以外の部分はすでに前に計算していてメモ化されているのでそれを使えばいい
6
4
func countBits (n int ) []int {
7
- bitCounts := make ([]int , n + 1 )
8
- powerOfTwo := 1
9
- for i := 1 ; i <= n ; i ++ {
10
- if i == powerOfTwo * 2 {
11
- powerOfTwo = i
12
- }
13
- bitCounts [i ] = 1 + bitCounts [i - powerOfTwo ]
14
- }
15
- return bitCounts
16
- }
17
-
18
- // 内側のループはnを2で割り続けるのでlog n回
19
- // 外側のループはn回なので、全体でO(n log n)になる
20
- func countBits2 (n int ) []int {
21
5
bitCounts := make ([]int , n + 1 )
22
6
for i := 0 ; i <= n ; i ++ {
23
- num := i
24
- count := 0
25
- for num > 0 {
26
- count += num % 2
27
- num /= 2
7
+ if i == 0 || i == 1 {
8
+ bitCounts [i ] = i
9
+ continue
28
10
}
29
- bitCounts [i ] = count
11
+ j := i & (i - 1 )
12
+ bitCounts [i ] = bitCounts [j ] + 1
30
13
}
31
14
return bitCounts
32
15
}
You can’t perform that action at this time.
0 commit comments