text: Count set bits in an integer | CPP implementation for recursive approach to find the number of set bits using Brian Kernighans Algorithm ; recursive function to count set bits ; base case ; driver code ; get value from user ; function calling
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { if ( n == 0 ) return 0 ; else return 1 + countSetBits ( n & ( n - 1 ) ) ; } int main ( ) { int n = 9 ; cout << countSetBits ( n ) ; return 0 ; }