ProgrammingHardTCS NQT · Wipro

How many integers in 0..15 are a power of two? Compute with this program.

How many integers in 0..15 are a power of two? Compute with this program.
#include <stdio.h>
int main(void) {
    int c = 0;
    for (unsigned x = 0; x < 16; x++)
        if (x && !(x & (x - 1))) c++;
    printf("%d", c);
}
  1. A. 3
  2. B. 6
  3. C. 4
  4. D. 5

Correct answer: C. 4

The powers of two in range are 1, 2, 4 and 8, and the check x && !(x & (x - 1)) excludes 0. Counting 0 as a power of two gives 5.

More C Programming questions

Exams that ask this topic