Count total set bits in all numbers from 1 to n | Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program
function countSetBits ( n ) { let bitCount = 0 ; for ( let i = 1 ; i <= n ; i ++ ) { bitCount += countSetBitsUtil ( i ) ; } return bitCount ; } function countSetBitsUtil ( x ) { if ( x <= 0 ) { return 0 ; } return ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( Math . floor ( x / 2 ) ) ; } let n = 4 ; document . write ( " " ) ; document . write ( countSetBits ( n ) ) ;