Sum of numbers with exactly 2 bits set | To count number of set bits ; To calculate sum of numbers ; To count sum of number whose 2 bit are set ; Driver program to test above function
function countSetBits ( n ) { let count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } function findSum ( n ) { let sum = 0 ; for ( let i = 1 ; i <= n ; i ++ ) if ( countSetBits ( i ) == 2 ) sum += i ; return sum ; } let n = 10 ; document . write ( findSum ( n ) ) ;