
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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 Articles
- 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
- How to count set bits in a floating point number in C?
- Python Count set bits in a range?
- Python program to count total set bits in all number from 1 to n.
- Count pairs in an array such that both elements has equal set bits in C++

Advertisements