ProgrammingVery hardCompetitive coding (CP)

How many adjacent pairs of 1 bits does 27 (binary 11011) have? The program counts the set bits of x & (x >> 1).

How many adjacent pairs of 1 bits does 27 (binary 11011) have? The program counts the set bits of x & (x >> 1).
#include <stdio.h>
int main(void) {
    unsigned x = 27, y = x & (x >> 1);
    int c = 0;
    while (y) { c += y & 1u; y >>= 1; }
    printf("%d", c);
}
  1. A. 3
  2. B. 1
  3. C. 2
  4. D. 4

Correct answer: C. 2

x & (x >> 1) has a 1 at each position where bit i and bit i + 1 of x are both set. For 11011 those are positions 0 and 3, so the count is 2.

More C Programming questions

Exams that ask this topic