ProgrammingHardTCS NQT · Accenture pattern
What will be the output of the following pseudocode (counting set bits using Brian Kernighan's trick, for each value 0 to 7)? (& is bitwise AND.)
What will be the output of the following pseudocode (counting set bits using Brian Kernighan's trick, for each value 0 to 7)? (& is bitwise AND.)
Function popcount(Integer n)
Integer c = 0
while (n != 0)
n = n & (n - 1)
c = c + 1
end while
return c
End Function
List result = empty list
for (each x from 0 to 7)
append(result, popcount(x))
end for
Print result- A. [0, 1, 1, 2, 1, 2, 2, 3]
- B. [0, 1, 2, 1, 2, 1, 2, 3]
- C. [1, 1, 2, 2, 1, 2, 2, 3]
- D. [0, 1, 1, 2, 2, 2, 3, 3]
Correct answer: A. [0, 1, 1, 2, 1, 2, 2, 3]
n & (n-1) clears the lowest set bit, so popcount counts 1-bits: 0->0, 1(1)->1, 2(10)->1, 3(11)->2, 4(100)->1, 5(101)->2, 6(110)->2, 7(111)->3.
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 (longest common prefix of a list of strings)? Function lcp(List strs) String prefix =…
- What will be the output of the following pseudocode (finding the kth smallest element by sorting)? (Arrays are indexed from 0.) Integer…
- What will be the output of the following pseudocode (number of ways to climb n stairs, taking 1 or 2 steps at a time)? Function…
- What will be the output of the following pseudocode (product of array except self, without using division)? (Arrays are indexed from 0.)…
- What will be the output of the following pseudocode (how many output rows a zigzag string conversion uses)? Function numRowsUsed(String s…
- What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.) Integer…