Sum of bit differences among all pairs | Java program to compute sum of pairwise bit differences ; traverse over all bits ; count number of elements with i 'th bit set ; Add " count ▁ * ▁ ( n ▁ - ▁ count ) ▁ * ▁ 2" to the answer ... ( n - count = unset bit count ) ; Driver prorgram
import java . io . * ; class GFG { static int sumBitDifferences ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) count ++ ; ans += ( count * ( n - count ) * 2 ) ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 5 } ; int n = arr . length ; System . out . println ( sumBitDifferences ( arr , n ) ) ; } }