- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C/C++ Program to Count set bits in an integer?

Here we will see how we can check number of set bits in an integer number. The set bits are 1’s in the binary representation of a number. For an example the number 13 has three set bits 1101. So the count will be 3.

To solve this problem, we will shift the number to the right, and if the LSb is 1, then increase count. Until the number becomes 0, it will run.

## Algorithm

### countSetBit()

begin count := 0 while count is not 0, do if LSb of n is set, then count := count + 1 end if n := n after shifting 1 bit to right done return count end

## Example

#include<iostream> using namespace std; int count_set_bit(int n) { int count = 0; while(n != 0) { if(n & 1 == 1) { count++; } n = n >> 1; //right shift 1 bit } return count; } int main() { int n; cout << "Enter a number: "; cin >> n; cout << "Number of set bits: " << count_set_bit(n); }

## Output

Enter a number: 29 Number of set bits: 4

This program will run in C and generates output, but when we want to compile in C++, it will return an error during compile time. It will say there are too many arguments are passed.

- Related Questions & Answers
- C/C++ Program to the Count set bits in an integer?
- Python Program to Count set bits in an integer
- Java Program to Count set bits in an integer
- Count set bits in an integer in C++
- Golang Program to count the set bits in an integer.
- C# program to count total set bits in a number
- Sort an array according to count of set bits in C++
- Count set bits in a range in C++
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- C# program to count total bits in a number
- Python Count set bits in a range?
- How to count set bits in a floating point number in C?
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++

Advertisements