ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int alt(unsigned x) {
    unsigned y = x ^ (x >> 1);
    return (y & (y + 1)) == 0;
}
int main(void) { printf("%d%d%d", alt(5), alt(10), alt(11)); }
  1. A. 100
  2. B. 010
  3. C. 110
  4. D. 111

Correct answer: C. 110

If x's bits alternate, x ^ (x >> 1) is a solid block of 1s from bit 0 up, and a value of the form 2^k − 1 satisfies y & (y + 1) == 0. 5 = 101 and 10 = 1010 alternate; 11 = 1011 gives y = 1110, which fails.

More C Programming questions

Exams that ask this topic