ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (& is bitwise AND and >> is a right shift.)

What will be the output of the following pseudocode? (& is bitwise AND and >> is a right shift.)
Integer c = 0
for (each x from 1 to 200)
    if ((x & (x >> 1)) == 0)
        c = c + 1
    end if
end for
Print c
  1. A. 33
  2. B. 40
  3. C. 54
  4. D. 100

Correct answer: C. 54

x & (x >> 1) is non-zero exactly when x has two adjacent 1-bits, so c counts numbers 1…200 whose binary form has no two neighbouring 1s. Numbers with exactly k bits and no adjacent 1s number Fibonacci F(k): 1, 1, 2, 3, 5, 8, 13 for k = 1…7, i.e. 33 below 128. For 8-bit numbers 128…200 (binary 10xxxxxx up to 11001000) the second bit must be 0, giving 10 followed by a 6-bit string with no adjacent 1s and value ≤ 200 − 128: all 21 such strings work, giving 54 in all. 33 stops at 127; 100 assumes half the numbers qualify.

More Pseudocode and Code Tracing questions

Exams that ask this topic