Count all pairs of an array which differ in K bits | Utility function to count total ones in a number ; Function to count pairs of K different bits ; let ans = 0 ; initialize final answer ; Check for K differ bit ; Driver Code
function bitCount ( n ) { let count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) > 0 ) ++ count ; n >>= 1 ; } return count ; } function countPairsWithKDiff ( arr , n , k ) { for ( let i = 0 ; i < n - 1 ; ++ i ) { for ( let j = i + 1 ; j < n ; ++ j ) { let xoredNum = arr [ i ] ^ arr [ j ] ; if ( k == bitCount ( xoredNum ) ) ++ ans ; } } return ans ; } let k = 2 ; let arr = [ 2 , 4 , 1 , 3 , 1 ] ; let n = arr . length ; document . write ( " " + k + " " + countPairsWithKDiff ( arr , n , k ) + " " ) ;