ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode (counting total set bits across 1..n)?

What will be the output of the following pseudocode (counting total set bits across 1..n)?
Function countSetBitsRange(Integer n)
    Integer total = 0
    for (each i from 1 to n)
        Integer x = i
        while (x > 0)
            total = total + (x mod 2)
            x = x / 2
        end while
    end for
    return total
End Function

Print countSetBitsRange(7)
  1. A. 10
  2. B. 12
  3. C. 11
  4. D. 14

Correct answer: B. 12

Counting set bits for 1..7: 1(1)+2(1)+3(2)+4(1)+5(2)+6(2)+7(3) = 1+1+2+1+2+2+3 = 12.

More Pseudocode and Code Tracing questions

Exams that ask this topic