Calculate the number of set bits for every number from 0 to N | Function to find the count of set bits in all the integers from 0 to n ; dp [ i ] will store the count of set bits in i ; Count of set bits in 0 is 0 ; For every number starting from 1 ; If current number is even ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) ; If current element is odd ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) + 1 ; Print the count of set bits in i ; Driver code
function findSetBits ( n ) { let dp = new Array ( n + 1 ) ; dp . fill ( 0 ) ; document . write ( dp [ 0 ] + " " ) ; for ( let i = 1 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) { dp [ i ] = dp [ parseInt ( i / 2 , 10 ) ] ; } else { dp [ i ] = dp [ parseInt ( i / 2 , 10 ) ] + 1 ; } document . write ( dp [ i ] + " " ) ; } } let n = 5 ; findSetBits ( n ) ;