Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f504fc

Browse files
committed
add 338
1 parent 19fcfd2 commit 8f504fc

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

‎problems/0338.counting-bits/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
# 0338.counting-bits
3+
4+
```text
5+
6+
338. 比特位计数
7+
8+
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
9+
10+
示例 1:
11+
12+
输入: 2
13+
输出: [0,1,1]
14+
示例 2:
15+
16+
输入: 5
17+
输出: [0,1,1,2,1,2]
18+
进阶:
19+
20+
给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
21+
要求算法的空间复杂度为O(n)。
22+
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
23+
24+
来源:力扣(LeetCode)
25+
链接:https://leetcode-cn.com/problems/counting-bits
26+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
27+
```

‎problems/0338.counting-bits/run.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package bits
2+
3+
import "fmt"
4+
5+
func Run() {
6+
bits := countBits(5)
7+
fmt.Println(bits)
8+
}
9+
10+
func countBits(num int) []int {
11+
bits := make([]int, num+1)
12+
for i := 0; i <= num; i++ {
13+
bits[i] = oneCount(i)
14+
}
15+
return bits
16+
}
17+
18+
func oneCount(n int) int {
19+
c := 0
20+
for ; n > 0; n &= n - 1 {
21+
c++
22+
}
23+
return c
24+
}

‎problems/0338.counting-bits/run_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
package bits
3+
4+
import "testing"
5+
6+
func TestRun(t *testing.T) {
7+
Run()
8+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /