logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Counting Set Bits in a Number

author
Generated by
Krishna Adithya Gaddam

08/12/2024

Bit Manipulation

Sign in to read full article

Counting the number of set bits in a binary representation of a number is a classic problem in computer science. In binary, a "set bit" is a bit that is equal to 1. Understanding how to count these bits efficiently can prove invaluable in algorithms, competitive programming, and real-world applications like data compression and error detection.

What Are Set Bits?

Let's based on the number 13. Its binary representation is:

13 in decimal = 1101 in binary

In this case, we have three set bits: the '1's in positions 0, 2, and 3. The goal is to determine how many such bits exist for any given integer.

Method 1: Using a Loop

The most straightforward method is to iteratively check each bit of the number. Here's how you could do it in Python:

def count_set_bits(n): count = 0 while n: count += n & 1 # Check the least significant bit n >>= 1 # Right shift the bits by 1 position return count # Example: print(count_set_bits(13)) # Output: 3

Explanation:

  1. We initialize a counter count to zero.
  2. Using a while loop, we continue as long as n is not zero.
  3. In each iteration, we check if the least significant bit (LSB) of n is set (using n & 1).
  4. We right shift n by 1 to check the next bit.
  5. When n becomes 0, the loop exits, and we return the count.

While this method is simple, it has a time complexity of O(k), where k is the number of bits in the number (which is O(log n) for an integer n).

Method 2: Brian Kernighan's Algorithm

Brian Kernighan's algorithm is an optimized method for counting set bits. It works by flipping the least significant set bit to 0 and counting how many times we can do this until the number becomes 0.

Here's how you can implement it:

def count_set_bits_bk(n): count = 0 while n: n &= (n - 1) # Clear the least significant set bit count += 1 return count # Example: print(count_set_bits_bk(13)) # Output: 3

Explanation:

  1. Similar to the previous method, we initialize a counter count.
  2. In the while loop, we continue until n becomes zero.
  3. The expression n & (n - 1) clears the least significant set bit from n.
  4. Every time we perform this operation, we increment our count, which effectively tells us how many set bits were present initially.

This algorithm runs in O(k) time as well, but it tends to perform better since, on average, it will execute fewer iterations than the previous method.

Method 3: Lookup Table for Small Integers

If you need to frequently count set bits for small integers, a great way to optimize is to use a precomputed lookup table. Here’s how you can set it up:

lookup = [0] * 256 for i in range(256): lookup[i] = (i & 1) + lookup[i // 2] def count_set_bits_lookup(n): count = 0 while n: count += lookup[n & 0xff] # Add the set bits from the last 8 bits n >>= 8 # Right shift by 8 bits return count # Example: print(count_set_bits_lookup(13)) # Output: 3

Explanation:

  1. We create a lookup table for bytes (0-255) that counts the set bits.
  2. The count_set_bits_lookup function retrieves the number of set bits from the last byte in n and reduces n by 8 bits in each iteration until it's zero.
  3. This approach is very fast for numbers since we can break down the counting process into simple lookups for smaller chunks.

Applications of Counting Set Bits

Counting set bits has various applications in coding and computational theory:

  • Performance Optimization: Algorithms that involve counting set bits often see performance boosts from the use of efficient counting methods.
  • Hash Functions: Set bits are commonly used in checksum calculations and hashing algorithms.
  • Data Compression: Understanding the distribution of set bits aids in making decisions about data storage and compression techniques.

By choosing the appropriate method for counting set bits based on your specific use case—whether prioritizing simplicity or performance—you can make significant strides in optimizing your algorithms. The world of bit manipulation is vast and powerful, and counting set bits is just the tip of the iceberg!

Popular Tags

Bit ManipulationSet BitsDSA

Share now!

Like & Bookmark!

Related Collections

  • Top 20 DSA Interview Questions Mastery

    23/09/2024 | DSA

  • Advanced Graph Interview Questions in Java

    16/11/2024 | DSA

  • Trees Interview Questions Using Java

    13/10/2024 | DSA

  • Advanced Priority Queue and Heap Interview Questions in Java

    16/11/2024 | DSA

  • DSA Mastery for Interviews

    23/09/2024 | DSA

Related Articles

  • Dynamic Arrays and Array Resize

    06/12/2024 | DSA

  • Building a Sudoku Solver Using Advanced Recursion and Backtracking in Java

    13/10/2024 | DSA

  • Efficient Algorithms with Bits

    08/12/2024 | DSA

  • Applications of Left Shift Operator in Data Structures and Algorithms

    08/12/2024 | DSA

  • Counting Set Bits in a Number

    08/12/2024 | DSA

  • Smallest Substring Containing All Characters of Another String

    15/11/2024 | DSA

  • Finding the Median of a Stream Using Heaps

    16/11/2024 | DSA

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design