text: Count set bits in an integer | C ++ implementation of the approach ; Lookup table ; Function to initialise the lookup table ; To initially generate the table algorithmically ; Function to return the count of set bits in n ; Driver code ; Initialise the lookup table
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int BitsSetTable256 [ 256 ] ; void initialize ( ) { BitsSetTable256 [ 0 ] = 0 ; for ( int i = 0 ; i < 256 ; i ++ ) { BitsSetTable256 [ i ] = ( i & 1 ) + BitsSetTable256 [ i / 2 ] ; } } int countSetBits ( int n ) { return ( BitsSetTable256 [ n & 0xff ] + BitsSetTable256 [ ( n >> 8 ) & 0xff ] + BitsSetTable256 [ ( n >> 16 ) & 0xff ] + BitsSetTable256 [ n >> 24 ] ) ; } int main ( ) { initialize ( ) ; int n = 9 ; cout << countSetBits ( n ) ; }