Solution Review: Get First Set Bit Position

In this lesson, we try to solve this algorithm using the right shift operator. Use a pen and a paper and try solving it.

Solution review

We check the right-most significant bit to see if the bit and & operation of 1 yields to 1.

In other words, we shift bits until the right MSB and & operation with 1 yields 1.

Algorithm

  • If n == 0, return;
  • Initialize k = 1
  • Loop
    • If ((n >> (k - 1)) & 1) == 0 increment the pointer k
    • Else, return k

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.