Solution Review: Get First Set Bit Position

In this lesson, we try to solve this algorithm using the left shift operator. Try solving it on your own.

Solution review

Imagine 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, and it yields 1.

Algorithm

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

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