- Related Questions & Answers
- C Program for Tower of Hanoi
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- C Program to Check if all digits of a number divide it
- C Program to Check if a Given String is a Palindrome?
- Write a program to Delete a Tree in C programming
- Write a C program to print “ Tutorials Point ” without using a semicolon
- Sum of the nodes of a Singly Linked List in C Program
- Sum of first n natural numbers in C Program
- C Program for simple interest?
- Area of a n-sided regular polygon with given Radius in C Program?
- Area of a leaf inside a square in C Program?
- C Program for Area of a square inscribed in a circle which is inscribed in a hexagon?

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

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.

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

#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); }

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.

Advertisements