Log In Sign Up
Day 55

Day 55: Counting Bits

55/60 Days

Day 55: Counting Bits #

Welcome to Day 55 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the problem of Counting Bits, which involves efficiently counting the number of set bits (1s) in binary representations of numbers.

What is Bit Counting? #

Bit counting, also known as population count or popcount, is the process of counting the number of 1s in the binary representation of a number. This operation is fundamental in many areas of computer science and has applications in cryptography, error correction, and more.

Approaches to Counting Bits #

We’ll explore several approaches to count bits, ranging from simple to more optimized algorithms:

1. Naive Approach #

This approach simply checks each bit of the number:

1def count_bits_naive(n):
2    count = 0
3    while n:
4        count += n & 1
5        n >>= 1
6    return count
7
8# Example usage
9print(count_bits_naive(13))  # Output: 3 (13 is 1101 in binary)

Time Complexity: O(log n), where n is the number.

2. Brian Kernighan’s Algorithm #

This algorithm uses the fact that subtracting 1 from a number flips all bits after the rightmost set bit:

1def …