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.
We'll cover the following...
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 -
- If