Integer bit counts and bit lengths [ref]
Problem¶
- Count set bits in
0b1011. - Find the bit lengths of
0,7, and8. - Count differing bits between
5and1. - Remove one set bit per iteration from
0b1011and count iterations. - Format
11in binary with and without its prefix.
Python solution¶
(0b1011).bit_count() # 3
[(x).bit_length() for x in (0, 7, 8)] # [0, 3, 4]
(5 ^ 1).bit_count() # 1
n, count = 0b1011, 0
while n:
n &= n - 1
count += 1
count # 3
bin(11) # '0b1011'
format(11, "b") # '1011'
Links¶
- 191. Number of Bits (Top Easy)
- 461. Hamming Distance (Top Easy)