Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 2859. Sum of Values at Indices With K Set Bits #57

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions leetcode/2859/2859. Sum of Values at Indices With K Set Bits.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package _859

func sumIndicesWithKSetBits(nums []int, k int) int {
sum := 0
for i, num := range nums {
if bitCount(i) == k {
sum += num
}
}
return sum
}

func bitCount(x int) int {
count := 0
for x > 0 {
count += x & 1
x >>= 1
}
return count
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package _859

import "testing"

func Test_sumIndicesWithKSetBits(t *testing.T) {
type args struct {
nums []int
k int
}
tests := []struct {
name string
args args
want int
}{
{
name: "one",
args: args{
nums: []int{5, 10, 1, 5, 2},
k: 1,
},
want: 13,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := sumIndicesWithKSetBits(tt.args.nums, tt.args.k); got != tt.want {
t.Errorf("sumIndicesWithKSetBits() = %v, want %v", got, tt.want)
}
})
}
}
Loading