Count Set | CPP program to find number of set bist in a number ; Recursive function to find number of set bist in a number ; Base condition ; If Least significant bit is set ; If Least significant bit is not set ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSetBits ( int n ) { if ( n == 0 ) return 0 ; if ( ( n & 1 ) == 1 ) return 1 + CountSetBits ( n >> 1 ) ; else return CountSetBits ( n >> 1 ) ; } int main ( ) { int n = 21 ; cout << CountSetBits ( n ) << endl ; return 0 ; }