How can Python bit operations be applied to efficiently count up the number of consecutive leading 1's in an integer's binary representation.
For instance,
ineger | binary representation | # consecutive leading 1's |
---|---|---|
0 | 0b0 | 0 |
1 | 0b1 | 1 |
2 | 0b10 | 1 |
3 | 0b11 | 2 |
4 | 0b100 | 1 |
5 | 0b101 | 1 |
6 | 0b110 | 2 |
7 | 0b111 | 3 |
This problem can be solved through string manipulation as lambda x: f"{x:b}0".index("0")
, but I am looking for a bitwise operation without string conversion.