The best programs are written so that computing machines can perform
them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist
who works with traditional aesthetic and literary forms as well as mathematical concepts, to
communicate the way that an algorithm works and to convince a reader that the results will be correct.
― Donald E. Knuth

Problem :-
Count the number of set bits in an integer.

Solution :-
We use a combination of bitwise AND operation & left shift operation to count the number of
set bits in an integer. See the implementation below.

#include<iostream>using namespace std;
// count the no. of set bits in a positive integerint countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
//mainint main() {
unsigned int num = 6;
unsigned int no_set_bits = countSetBits(num);
cout<<"\nNo. of set bits :: "<<no_set_bits;
cout<<endl;
return 0;
}

#include<iostream>using namespace std;
// count the no. of set bits in a positive integerint countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
//mainint main() {
unsigned int num = 6;
unsigned int no_set_bits = countSetBits(num);
cout<<"\nNo. of set bits :: "<<no_set_bits;
cout<<endl;
return 0;
}