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 ; initialize final answer ; Check for K differ bit ; Driver code
< ? php function bitCount ( $ n ) { $ count = 0 ; while ( $ n ) { if ( $ n & 1 ) ++ $ count ; $ n >>= 1 ; } return $ count ; } function countPairsWithKDiff ( $ arr , $ n , $ k ) { $ ans = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; ++ $ i ) { for ( $ j = $ i + 1 ; $ j < $ n ; ++ $ j ) { $ xoredNum = $ arr [ $ i ] ^ $ arr [ $ j ] ; if ( $ k == bitCount ( $ xoredNum ) ) ++ $ ans ; } } return $ ans ; } $ k = 2 ; $ arr = array ( 2 , 4 , 1 , 3 , 1 ) ; $ n = count ( $ arr ) ; echo " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " , $ k , " ▁ are ▁ " , countPairsWithKDiff ( $ arr , $ n , $ k ) , " STRNEWLINE " ; ? >