basics · intermediate · ~15 min

Population count of a bitset

Count set bits across an array of words.

Challenge

Implement:

int bitset_count(const uint32_t *bs, int nwords);

Return the total number of set bits across a bitset stored as nwords 32-bit words.

Input format

A word array bs and its length nwords.

Output format

Total set bits across all words.

Constraints

nwords==0 returns 0.

Starter code

#include <stdint.h>
#include <stddef.h>
/* Total number of set bits across a bitset of nwords 32-bit words. */
int bitset_count(const uint32_t *bs,int nwords){ (void)bs;(void)nwords; return 0; }

Common mistakes

Reading past nwords; summing values instead of set bits.

Edge cases to handle

A bitset represents a set of small integers compactly.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.