ProgrammingHardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode? (>> is right shift, & is bitwise AND)
What will be the output of the following pseudocode? (>> is right shift, & is bitwise AND)
Integer bits[0..15], total = 0
bits[0] = 0
for (each i from 1 to 15)
bits[i] = bits[i >> 1] + (i & 1)
end for
for (each i from 0 to 15)
total = total + bits[i]
end for
Print bits[13], total- A. 3 32
- B. 3 30
- C. 2 32
- D. 4 32
Correct answer: A. 3 32
bits[i] reuses the count for i with its last bit removed, so bits[i] is the number of 1's in i: bits[13] = bits[1101₂] = 3. Over 0 to 15, each of the 4 bit positions is 1 in exactly 8 numbers: total 32.
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? (Arrays are indexed from 0) Integer a[6] = {3, 2, 2, 3, 4, 3}, k = 0, val = 3 for…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 7, c = 1 for (each…
- What will be the output of the following pseudocode? Integer count = 0 String last = "" Procedure gen(String s, Integer n) if (length(s)…
- What will be the output of the following pseudocode? Integer p[4] = {2, 0, 3, 1} // coefficients of 2x³ + 0x² + 3x + 1 Integer x = 3, m =…
- What is the time complexity of the following pseudocode, as a function of n? Procedure f(Integer n) if (n <= 1) return end if for (each i…
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i i <= n; i = i + 1) for (j = 1; j <= n; j = j 2)…