Count pairs with set bits sum equal to K | Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Sum of set bits in both the integers ; If current pair satisfies the given condition ; Driver code
function countSetBits ( n ) { var count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } function pairs ( arr , n , k ) { var count = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { var sum = countSetBits ( arr [ i ] ) + countSetBits ( arr [ j ] ) ; if ( sum == k ) count ++ ; } } return count ; } var arr = [ 1 , 2 , 3 , 4 , 5 ] ; var n = arr . length ; var k = 4 ; document . write ( pairs ( arr , n , k ) ) ;