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- A. 33
- B. 40
- C. 54
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise…
- What will be the output of the following pseudocode? (& is bitwise AND.) Integer c = 0, x for (each i from 0 to 63) x = i while (x > 0) x…
- What will be the output of the following pseudocode? Integer n = 30, c = 0, j for (each i from 1 to n) j = i while (j <= n) c = c + 1 j =…
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1; i <= 100; i = i 2) for (j = i; j <= 100; j = j + 1) c = c +…
- What will be the output of the following pseudocode? // 32-bit signed integers; overflow wraps around (two's complement); / truncates…
- What is the time complexity of the following pseudocode, as a function of n? for (i = n; i > 0; i = i / 2) for (j = 0; j < i; j = j + 1)…