ProgrammingHardProduct company OA

What is printed?

What is printed?
int h(unsigned a, unsigned b) {
    int c = 0;
    for (unsigned x = a ^ b; x; x >>= 1) c += x & 1;
    return c;
}
int main(void) { printf("%d %d", h(29, 15), h(0xFF, 0x100)); }
  1. A. 3 9
  2. B. 2 9
  3. C. 2 1
  4. D. 4 8

Correct answer: B. 2 9

a ^ b has a 1 wherever the two numbers differ, and the loop counts those 1s (the Hamming distance). 29 = 11101 and 15 = 01111 differ in 2 places. 0xFF ^ 0x100 = 0x1FF, nine 1s. '2 1' assumes 0xFF and 0x100 differ in one bit.

More C Programming questions

Exams that ask this topic