Skip to content

Commit 3c6cac4

Browse files
committed
✨ Add solution and testcases to problem 338
1 parent 267715d commit 3c6cac4

File tree

3 files changed

+26
-12
lines changed

3 files changed

+26
-12
lines changed

leetcode/301-400/0338.Counting-Bits/README.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
# [338.Counting Bits][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
74

5+
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
6+
87
**Example 1:**
98

109
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
10+
Input: n = 2
11+
Output: [0,1,1]
12+
```
13+
14+
**Example 2:**
15+
16+
```
17+
Input: n = 5
18+
Output: [0,1,1,2,1,2]
1319
```
1420

1521
## 题意
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(n int) []int {
4+
res := make([]int, n + 1)
5+
for i := 1; i < n + 1; i++ {
6+
if i % 2 == 0 {
7+
res[i] = res[i/2]
8+
} else {
9+
res[i] = res[i/2] + 1
10+
}
11+
}
12+
return res
513
}

leetcode/301-400/0338.Counting-Bits/Solution_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs int
14+
expect []int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase", 2, []int{0,1,1}},
17+
{"TestCase", 5, []int{0,1,1,2,1,2}},
18+
{"TestCase", 10, []int{0,1,1,2,1,2,2,3,1,2,2}},
1919
}
2020

2121
// 开始测试

0 commit comments

Comments
 (0)