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: using System ; using System . Collections . Generic ; class GFG { static int [ ] BitsSetTable256 = new int [ 256 ] ; public static void initialize ( ) { BitsSetTable256 [ 0 ] = 0 ; for ( int i = 0 ; i < 256 ; i ++ ) { BitsSetTable256 [ i ] = ( i & 1 ) + BitsSetTable256 [ i / 2 ] ; } } public static int countSetBits ( int n ) { return ( BitsSetTable256 [ n & 0xff ] + BitsSetTable256 [ ( n >> 8 ) & 0xff ] + BitsSetTable256 [ ( n >> 16 ) & 0xff ] + BitsSetTable256 [ n >> 24 ] ) ; } public static void Main ( String [ ] args ) { initialize ( ) ; int n = 9 ; Console . Write ( countSetBits ( n ) ) ; } }