![]() |
In C programming, counting set bits is the process of determining the number of bits that are set to 1 in a binary number. This operation is useful in various applications including network programming, error detection, and cryptography. In this article, we will learn how to count the number of set bits (1s) in a binary number in C. We will also look at different methods to achieve this. Table of Content How to Count Set Bits in C?Counting set bits involves determining how many 1s are present in the binary representation of a number. There are several methods to achieve this in C. Method 1: Using Bitwise AND and Shift OperatorIn this method, we repeatedly check each bit of the number using the bitwise AND operator and right shift the number to move to the next bit. Example: Input: C Program to Count Set Bits using Bitwise AND and Shift Operator
Output Number of set bits: 5 Time Complexity: O(logn) Method 2: Using Brian Kernighan’s AlgorithmThis efficient method reduces the number of iterations by turning off the rightmost set bit in each iteration. Example: Input: C Program to Count Set Bits using Brian Kernighan’s Algorithm
Output Number of set bits: 5 Time Complexity: O(k), where k is the number of set bits. Space Complexity: O(1) Method 3: Using Lookup TableThis method precomputes the number of set bits for all possible bytes (0 to 255) and uses it for fast lookups. Example: Input: C Program to Count Set Bits using Lookup Table
Output Number of set bits: 5 Time Complexity: O(1) Space Complexity: O(1) (for the lookup table of size 256 bytes) ConclusionCounting set bits is a fundamental operation in many applications. We have explored three different methods to count set bits in C: using bitwise AND and shift operator, Brian Kernighan’s algorithm, and a lookup table. Each method has its own advantages and can be chosen based on the specific requirements of the application. |
Reffered: https://www.geeksforgeeks.org
C Language |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 22 |