ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (finding the 1-based position of the rightmost set bit)? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode (finding the 1-based position of the rightmost set bit)? (All variables are integers, so / is integer division.)
Function rightmostSetBit(Integer n)
    Integer pos = 0
    while (n mod 2 == 0)
        n = n / 2
        pos = pos + 1
    end while
    return pos + 1
End Function

Print rightmostSetBit(18), rightmostSetBit(12)
  1. A. 2 3
  2. B. 1 2
  3. C. 3 2
  4. D. 2 2

Correct answer: A. 2 3

18 = 10010 in binary; its rightmost set bit is at position 2 (counting from 1, LSB side). 12 = 1100 in binary; its rightmost set bit is at position 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic