- 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

Counting set bits means counting 1’S of the given integer. For this, we have multiple solutions that can be applied. For this case, we have a binary number( binary representation of an integer), for which we have to count the number of 1’s off the string.

To count the number of 1’s, we will take the string, traverse each element and count all the 1’s of the string. For example, if we input 17 the output will be 2 because the binary of 17 is 10001 that contains two 1's.

Input: Enter a positive integer: 6 Output: 2

The binary representation of 6 is 110 which has 2 set bits

This iterative approach requires one iteration per bit. It runs through all the bits of the number. Iteration terminates when no more bits are set. In the worst case, on a 32-bit word with only the most significant bit set, it will loop through 32 iterations. This solution is the simplest one and useful if 1's are sparse and among the least significant bits.

#include <stdio.h> int main(void) { unsigned int n = 34; for (c = 0; n; n >>= 1) { c += n & 1; } printf("%d\n", c); }

- Related Questions & Answers
- C/C++ 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.
- Java Program to Count set bits in an integer
- Python Program to Count 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++
- C# program to count total bits in a number
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++
- Count the number of holes in an integer in C++
- How to count set bits in a floating point number in C?
- Count pairs in an array such that both elements has equal set bits in C++
- Python Count set bits in a range?

Advertisements