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
  1. A. [0, 1, 1, 2, 1, 2, 2, 3]
  2. B. [0, 1, 2, 1, 2, 1, 2, 3]
  3. C. [1, 1, 2, 2, 1, 2, 2, 3]
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic