ProgrammingHardProduct company OA

What is printed?

What is printed?
int f(unsigned x) {
    int c = 0;
    while (x) { c += x & 1; x >>= 2; }
    return c;
}
int main(void) { printf("%d", f(0xFF) + f(0xAA)); }
  1. A. 0
  2. B. 4
  3. C. 8
  4. D. 12

Correct answer: B. 4

Shifting by 2 each time means only bits 0, 2, 4, 6 … are ever tested. 0xFF has all four of those set (4); 0xAA = 1010 1010 has ones only in odd positions (0). '12' counts every set bit of both.

More C Programming questions

Exams that ask this topic