Skip to content

Commit d79834a

Browse files
committed
refactor Counting Bits
1 parent cdcc32c commit d79834a

File tree

1 file changed

+5
-22
lines changed

1 file changed

+5
-22
lines changed

go/counting_bits.go

+5-22
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,15 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4-
// 2の冪乗の時はMSBのみが1になる
5-
// それ以外の場合はMSB以外の部分はすでに前に計算していてメモ化されているのでそれを使えばいい
64
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 {
215
bitCounts := make([]int, n+1)
226
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
2810
}
29-
bitCounts[i] = count
11+
j := i & (i - 1)
12+
bitCounts[i] = bitCounts[j] + 1
3013
}
3114
return bitCounts
3215
}

0 commit comments

Comments
 (0)