ProgrammingHardGATE CS · Competitive coding (CP)

How many integers x in 1..255 have exactly four set bits? Compute with this program.

How many integers x in 1..255 have exactly four set bits? Compute with this program.
#include <stdio.h>
int main(void) {
    int c = 0;
    for (unsigned x = 1; x <= 255; x++) {
        unsigned t = x;
        int bits = 0;
        while (t) { bits += t & 1u; t >>= 1; }
        if (bits == 4) c++;
    }
    printf("%d", c);
}
  1. A. 56
  2. B. 70
  3. C. 64
  4. D. 72

Correct answer: B. 70

Choosing 4 of the 8 bit positions gives C(8, 4) = 70 values, and the loop counts exactly those x in 1..255.

More C Programming questions

Exams that ask this topic