From f735d383a1d29ae41131180120ad7a09e2218b6a Mon Sep 17 00:00:00 2001 From: Seongjun Kim Date: Tue, 11 Mar 2025 15:28:40 -0700 Subject: [PATCH] week14 --- counting-bits/bus710.go | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 counting-bits/bus710.go diff --git a/counting-bits/bus710.go b/counting-bits/bus710.go new file mode 100644 index 000000000..b0ec81902 --- /dev/null +++ b/counting-bits/bus710.go @@ -0,0 +1,53 @@ +package hello + +import ( + "fmt" + "reflect" + "strings" + "testing" +) + +func countBits(n int) []int { + r := make([]int, 0) + + for i := range n + 1 { + b := fmt.Sprintf("%b", i) + cnt := strings.Count(string(b), "1") + r = append(r, cnt) + } + + return r +} + +func Test_countBits(t *testing.T) { + type args struct { + n int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case 1", + args: args{ + n: 2, + }, + want: []int{0, 1, 1}, + }, + { + name: "case 2", + args: args{ + n: 5, + }, + want: []int{0, 1, 1, 2, 1, 2}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := countBits(tt.args.n); !reflect.DeepEqual(got, tt.want) { + t.Errorf("countBits() = %v, want %v", got, tt.want) + } + }) + } +}