Count all pairs of an array which differ in K bits | Java program to count all pairs with bit difference as k ; Utility function to count total ones in a number ; Function to count pairs of K different bits ; long ans = 0 ; initialize final answer ; Check for K differ bit ; Driver code
import java . io . * ; class GFG { static int bitCount ( int n ) { int count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) > 0 ) ++ count ; n >>= 1 ; } return count ; } static long countPairsWithKDiff ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n - 1 ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int xoredNum = arr [ i ] ^ arr [ j ] ; if ( k == bitCount ( xoredNum ) ) ++ ans ; } } return ans ; } public static void main ( String [ ] args ) { int k = 2 ; int arr [ ] = { 2 , 4 , 1 , 3 , 1 } ; int n = arr . length ; System . out . println ( " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " + k + " ▁ are ▁ " + countPairsWithKDiff ( arr , n , k ) + "NEW_LINE"); } }