ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (number of bits needed to represent n in binary)?

What will be the output of the following pseudocode (number of bits needed to represent n in binary)?
Function bitsNeeded(Integer n)
    Integer c = 0
    while (n > 0)
        n = n >> 1
        c = c + 1
    end while
    return c
End Function

Print bitsNeeded(37)
  1. A. 5
  2. B. 6
  3. C. 7
  4. D. 37

Correct answer: B. 6

37 in binary is 100101, which is 6 bits long; right-shifting 37 to 0 takes exactly 6 shifts.

More Pseudocode and Code Tracing questions

Exams that ask this topic