text: Count set bits in an integer | Lookup table ; Function to initialise the lookup table ; To initially generate the table algorithmically ; Function to return the count of set bits in n ; Initialise the lookup table
code: var BitsSetTable256 = Array . from ( { length : 256 } , ( _ , i ) => 0 ) ; function initialize ( ) { BitsSetTable256 [ 0 ] = 0 ; for ( var i = 0 ; i < 256 ; i ++ ) { BitsSetTable256 [ i ] = ( i & 1 ) + BitsSetTable256 [ parseInt ( i / 2 ) ] ; } } function countSetBits ( n ) { return ( BitsSetTable256 [ n & 0xff ] + BitsSetTable256 [ ( n >> 8 ) & 0xff ] + BitsSetTable256 [ ( n >> 16 ) & 0xff ] + BitsSetTable256 [ n >> 24 ] ) ; } initialize ( ) ; var n = 9 ; document . write ( countSetBits ( n ) ) ;