Count Set Bits (Lookup Table)

beginner
8 min

Count Set Bits (Lookup Table)

Welcome to another exciting lesson on CodeYourCraft! Today, we're diving into a fascinating topic called Count Set Bits using a Lookup Table. This lesson is designed for beginners and intermediate learners, so let's get started! šŸŽÆ

What are Set Bits?

In simple terms, a set bit is a 1 in a binary representation of a number. For example, the binary representation of the number 7 is 111, and it has 3 set bits. šŸ’”

Why Count Set Bits?

Counting set bits can be useful in many real-world applications such as data compression, network communications, and computer graphics. It's a great exercise to understand binary representations better. āœ…

The Lookup Table Approach

Instead of counting set bits recursively or using bitwise operations, we'll use a lookup table to make the process faster and easier to understand. šŸ“

Creating the Lookup Table

The lookup table stores the number of 1's for all possible integers from 0 to 31. Here's how to create it:

  1. Initialize an array table of size 32.
  2. Iterate from 0 to 31 and count the number of set bits in each number using a bitwise operation (we'll learn this soon).
  3. Store the count in the corresponding index of the table array.

Now, we have a lookup table that can count set bits for any number in a constant time! šŸŽÆ

Counting Set Bits using the Lookup Table

To count the set bits of a number n, we'll split n into two parts: n & (n - 1) and n >> 1. The first part has one less set bit than the original number, and the second part has the same set bits as the original number shifted one place to the right. šŸ’”

Here's the complete function using the lookup table:

python
def count_set_bits(n): table = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] # Split the number into two parts part1 = n & (n - 1) part2 = n >> 1 # Count the set bits in each part count1 = table[part1] count2 = table[part2] # Add one to account for the last set bit in part1 that might have been lost count = count1 + count2 + (n > 0) return count

šŸ“ Note: The (n > 0) check ensures we don't miss the first set bit when the number is zero.

Practical Examples

Let's count the set bits for a few numbers:

  1. 7 (binary: 111): count_set_bits(7) returns 3
  2. 10 (binary: 1010): count_set_bits(10) returns 2
  3. 0: count_set_bits(0) returns 0

Quiz Time!

Quick Quiz
Question 1 of 1

Which number has the most set bits among 5, 7, and 10?

And that's it for today! You now have a solid understanding of how to count set bits using a lookup table. In the next lesson, we'll explore bitwise operations in more detail, which will help you master this approach even further.

Until then, happy coding! šŸš€

P.S. Stay tuned for more engaging and practical lessons on Data Structures and Algorithms at CodeYourCraft! šŸ’”