Skip to content

Commit 673403b

Browse files
authored
Merge pull request #1097 from bus710/week14
[bus710] Week 14
2 parents f6d101c + f735d38 commit 673403b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

counting-bits/bus710.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package hello
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"strings"
7+
"testing"
8+
)
9+
10+
func countBits(n int) []int {
11+
r := make([]int, 0)
12+
13+
for i := range n + 1 {
14+
b := fmt.Sprintf("%b", i)
15+
cnt := strings.Count(string(b), "1")
16+
r = append(r, cnt)
17+
}
18+
19+
return r
20+
}
21+
22+
func Test_countBits(t *testing.T) {
23+
type args struct {
24+
n int
25+
}
26+
tests := []struct {
27+
name string
28+
args args
29+
want []int
30+
}{
31+
{
32+
name: "case 1",
33+
args: args{
34+
n: 2,
35+
},
36+
want: []int{0, 1, 1},
37+
},
38+
{
39+
name: "case 2",
40+
args: args{
41+
n: 5,
42+
},
43+
want: []int{0, 1, 1, 2, 1, 2},
44+
},
45+
}
46+
for _, tt := range tests {
47+
t.Run(tt.name, func(t *testing.T) {
48+
if got := countBits(tt.args.n); !reflect.DeepEqual(got, tt.want) {
49+
t.Errorf("countBits() = %v, want %v", got, tt.want)
50+
}
51+
})
52+
}
53+
}

0 commit comments

Comments
 (0)