Counting set bits means determining how many bits in a binary representation of a number are set to 1.
Example
Input: n = 103 (01100111)
Output: 5
Explanation: The binary representation of 103 is 01100111. Hence, the number of set bits is 5.
Input: n = 15 (1111)
Output: 4
Explanation: The binary representation of 15 is 1111. Thus, the number of set bits is 4.
In C++, we have several different methods to count the number of set bits in a number.
Using Bitwise AND with Shift Operator
In this method, we use the bitwise AND operator (&) to check each bit of the number. We process all bits by repeatedly right-shifting the number once after checking whether each one is set.
Code Implementation
C++
// C++ Program to count the number of set bits in a number
// using AND operation and left shifting
#include <iostream>
using namespace std;
int countSetBits(int n) {
int count = 0;
// Runs till the n is greater than 0
while (n) {
// Check the least significant bit
count += n & 1;
// Right shift the number by 1
n >>= 1;
}
return count;
}
int main() {
int n = 103; // Binary: 01100111
// Counting and printing set bits in n
cout << countSetBits(n) << endl;
return 0;
}
Time Complexity: O(log2n), where n is the given number.
Auxiliary Space: O(1)
Using Brian Kernighan’s Algorithm
Brian Kernighan’s algorithm is an efficient method for counting the number of set bits. It works by resetting the rightmost set bit in each iteration in till the number becomes equal to zero. So the number of times we iterate is the number of set bits in it. To reset the rightmost bit, we use the formula
n &= (n - 1);
where n is the given number.
Code Implementation
C++
// C++ Program to count the number of set bits in a number
// using Brian Kernighan's Algorithm
#include <iostream>
using namespace std;
int countSetBits(int n) {
int count = 0;
// Runs till n becomes 0
while (n) {
// Turn off/reset the rightmost set bit
n &= (n - 1);
// Increment the count of set bits
count++;
}
return count;
}
int main() {
int n = 103; // Binary: 01100111
// Counting and printing set bits in n
cout << countSetBits(n) << endl;
return 0;
}
Time Complexity: O(log2n), where n is the given number.
Auxiliary Space: O(1)
The worst case for Brian Kernighan’s algorithm will be when all the bits are set where it will become equal to the first method. But other than that, it will outperform the first method in every case.
Using Lookup Table
In this method, number of set bits for all possible byte values (0–255) are computed and stored in an table for quick lookups.
Code Implementation
C++
// C++ Program to count the number of set bits in a number
// using a lookup table
#include <iostream>
using namespace std;
// Lookup table to store the number of set bits for bytes
unsigned char bitsSetTable256[256];
// Function to initialize the lookup table
void initialize() {
bitsSetTable256[0] = 0;
for (int i = 1; i < 256; i++) {
bitsSetTable256[i] = (i & 1) + bitsSetTable256[i / 2];
}
}
int countSetBits(int n) {
return bitsSetTable256[n & 0xFF] +
bitsSetTable256[(n >> 8) & 0xFF] +
bitsSetTable256[(n >> 16) & 0xFF] +
bitsSetTable256[(n >> 24) & 0xFF];
}
int main() {
// Initialize the lookup table
initialize();
int n = 103; // Binary: 01100111
// Counting and printing set bits in n
cout << countSetBits(n) << endl;
return 0;
}
Time Complexity: O(1), time for creating lookup table is not considered.
Auxiliary Space: O(1), space for lookup table not considered.
Similar Reads
Counting Set bit in C 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 b
4 min read
bitset set() function in C++ STL bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1. Syntax: set(int index, bool val) Parameter: The function accepts tw
2 min read
bitset all() function in C++ STL The bitset::all() is a built-in function in C++ STL which returns True if all bits are set in the binary representation of a number if it is initialized in the bitset. It returns False if all the bits are not set. Syntax: bool bitset_name.all() Parameter: This function does not accepts any parameter
2 min read
Clearing Bits in C++ In C++ programming, clearing a bit involves setting the value of a specific bit in a binary number to 0. This operation is useful in various applications such as bit masking, controlling hardware, and optimizing algorithms.In this article, we will learn how to clear a bit at a given position in a bi
4 min read
CSES Solutions - Counting Bits Given an integer N (1 ⤠N ⤠1015), the task is to count the number of one bits in the binary representations of integers between 1 and N. Examples: Input: N = 7Output: 12Explanation: Binary representations of 1: 001-> Set bits = 1Binary representations of 2: 010-> Set bits = 1Binary representa
9 min read
bitset size() in C++ STL bitset::size() is a built-in STL in C++ which returns the total number of bits. Syntax: bitset_name.size() Parameter: The function accepts no parameter. Return Value: The function returns an integral value which signifies the number of bits. It eventually returns the size that has been given while i
2 min read
bitset none() in C++ STL bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set. Syntax: bool none() Parameter: The function accepts no parameter. Return Value: The function returns a boolean. The boolean value is True if none of its bits are s
2 min read
Setting Bits in C In C programming, setting a bit is the process of setting a specific bit of a binary number to 1. This operation is crucial in various applications, including memory management, data processing, and hardware control.In this article, we will learn how to set a bit at a given position in a binary numb
3 min read
bitset::flip() in C++ STL bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only. Syntax: bitset_name.flip(int pos) Parameter:
2 min read
Extract Bits in C++ Extracting bits from a given number involves extracting 'k' bits starting from a specified position 'pos' by using bitwise operations like AND (&) and shifts (<<, >>). In this article, we will learn how to extract bits in C++.Example:Input:num = 214k = 3pos = 2Output:5Extracting Bits
2 min read