Skip to content

Commit 6fa477d

Browse files
committed
bit 338
1 parent dc49329 commit 6fa477d

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

go/bit/338/338.比特位计数.go

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
* @lc app=leetcode.cn id=338 lang=golang
3+
*
4+
* [338] 比特位计数
5+
*
6+
* https://leetcode.cn/problems/counting-bits/description/
7+
*
8+
* algorithms
9+
* Easy (78.65%)
10+
* Likes: 1280
11+
* Dislikes: 0
12+
* Total Accepted: 316.7K
13+
* Total Submissions: 402.6K
14+
* Testcase Example: '2'
15+
*
16+
* 给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans
17+
* 作为答案。
18+
*
19+
*
20+
*
21+
*
22+
*
23+
* 示例 1:
24+
*
25+
*
26+
* 输入:n = 2
27+
* 输出:[0,1,1]
28+
* 解释:
29+
* 0 --> 0
30+
* 1 --> 1
31+
* 2 --> 10
32+
*
33+
*
34+
* 示例 2:
35+
*
36+
*
37+
* 输入:n = 5
38+
* 输出:[0,1,1,2,1,2]
39+
* 解释:
40+
* 0 --> 0
41+
* 1 --> 1
42+
* 2 --> 10
43+
* 3 --> 11
44+
* 4 --> 100
45+
* 5 --> 101
46+
*
47+
*
48+
*
49+
*
50+
* 提示:
51+
*
52+
*
53+
* 0 <= n <= 10^5
54+
*
55+
*
56+
*
57+
*
58+
* 进阶:
59+
*
60+
*
61+
* 很容易就能实现时间复杂度为 O(n log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
62+
* 你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount )
63+
*
64+
*
65+
*
66+
*
67+
*/
68+
package jzoffer
69+
70+
import (
71+
"math/bits"
72+
)
73+
74+
// @lc code=start
75+
func countBitsBuiltIn(n int) (res []int) {
76+
77+
// fmt.Printf("%b,%b,%b", 63&(1<<7-1), (1<<7 - 1), 1<<7)
78+
79+
res = make([]int, n+1)
80+
for i := 0; i <= n; i++ {
81+
res[i] = bits.OnesCount32(uint32(i))
82+
}
83+
return res
84+
}
85+
86+
// 使用Brain Kcrnighan算法每次将最低位的二进制位1置为0,直到x为0
87+
// 如 二进制数 101 & 100 => 100 11 & 10 => 10
88+
func onesCount(x int) (ones int) {
89+
for ; x > 0; x &= x - 1 {
90+
ones++
91+
}
92+
return
93+
}
94+
95+
func countBitsBKAlgorithm(n int) []int {
96+
bits := make([]int, n+1)
97+
for i := range bits {
98+
bits[i] = onesCount(i)
99+
}
100+
return bits
101+
}
102+
103+
// 动态规划,上面的BK算法需要O(nlog(n))时间复杂度
104+
// 最低设置位 x & (x-1) 会将最低位的1置为0
105+
func countBits(n int) []int {
106+
bits := make([]int, n+1)
107+
for i := 1; i <= n; i++ {
108+
bits[i] = bits[i&(i-1)] + 1
109+
}
110+
return bits
111+
}
112+
113+
// @lc code=end

0 commit comments

Comments
 (0)