ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int f(unsigned x) {
    int c = 0;
    while (x & (x >> 1)) { x &= x >> 1; c++; }
    return c + (x != 0);
}
int main(void) { printf("%d %d", f(0xEE), f(0x7F0F)); }
  1. A. 6 11
  2. B. 3 4
  3. C. 2 6
  4. D. 3 7

Correct answer: D. 3 7

x &= x >> 1 shortens every run of consecutive 1s by one bit, so the loop counts how many times this can happen before no two adjacent 1s remain; adding 1 for the bits left gives the longest run of 1s. 0xEE = 1110 1110 → 3; 0x7F0F = 0111 1111 0000 1111 → 7. '6 11' counts all set bits.

More C Programming questions

Exams that ask this topic