ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
unsigned inv(unsigned g) {
    unsigned n = 0;
    for (; g; g >>= 1)
        n ^= g;
    return n;
}
int main(void) {
    printf("%u", inv(13));
}
  1. A. 13
  2. B. 8
  3. C. 9
  4. D. 11

Correct answer: C. 9

This loop computes the prefix XOR of the bits, which inverts the Gray code. For 13 it gives 13 ^ 6 ^ 3 ^ 1 = 9, and the Gray code of 9 is 9 ^ 4 = 13.

More C Programming questions

Exams that ask this topic