GATE Computer ScienceHardGATE CS (PYQ pattern)

unsigned f(unsigned x) { unsigned c = 0; while (x) { x &= x - 1; c++; } return c; } unsigned g(unsigned x) { return x & ~(x - 1); } unsigned h(unsigned x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; return x - (x >> 1); } What is f(0xB4) * 100 + g(0xB4) + h(0xB4)?

  1. A. 659
  2. B. 704
  3. C. 532
  4. D. 660

Correct answer: C. 532

0xB4 = 1011 0100. f clears the lowest set bit each time, so it counts ones: 4. x & ~(x - 1) equals x & -x, the lowest set bit: 4. h smears the top bit rightwards (giving 1111 1111 = 255 for any byte-sized x) and x - (x >> 1) keeps only the highest set bit: 128. Total 400 + 4 + 128 = 532.

More Programming and Data Structures (GATE) questions

Exams that ask this topic