← Bit Manipulation

Drill #83 — Count set bits

Easy Bit Counting Bit Manipulation

In plain English: Count how many 1s appear in the binary form of a number.

n & (n-1) clears the lowest set bit each time — loop until n is zero and count the iterations.

Prompt

Count the number of 1-bits (set bits) in the binary representation of a non-negative integer.

Try to write it from scratch before scrolling down.

Solution

def count_bits(n):
    count = 0
    while n:
        n &= n - 1  # clear lowest set bit
        count += 1
    return count

# Test: count_bits(11) == 3  (1011 in binary)
# Test: count_bits(128) == 1  (10000000)
# Test: count_bits(0) == 0
O(k) time where k = number of set bits · O(1) space

Related Micro Drills

← Drill #82 Drill #84 →