Open In App

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

Last Updated : 14 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Write an efficient program to count number of 1s in binary representation of an integer.

Examples :

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits
setbit

1. Simple Method

Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.


Output
2

Recursive Approach :


Output
2

Please refer complete article on

Count set bits in an integer

for more details!


Next Article
Article Tags :

Similar Reads