ProgrammingHardCompetitive coding (CP)

How many values of n in 1..50 have bit 2 set (the value 4)? Compute with this program.

How many values of n in 1..50 have bit 2 set (the value 4)? Compute with this program.
#include <stdio.h>
int main(void) {
    int c = 0;
    for (unsigned n = 1; n <= 50; n++)
        if ((n >> 2) & 1u) c++;
    printf("%d", c);
}
  1. A. 12
  2. B. 47
  3. C. 24
  4. D. 25

Correct answer: C. 24

(n >> 2) & 1 tests bit 2, which is set in the runs 4-7, 12-15, ..., 44-47: six runs of four, 24 values (49 and 50 have it clear). 12 counts multiples of 4, 47 drops the & 1 and counts every n >= 4, and 25 wrongly adds 49 or 50.

More C Programming questions

Exams that ask this topic