Sum of bit differences among all pairs | PHP program to compute sum of pairwise bit differences ; Initialize result ; traverse over all bits ; count number of elements with i 'th bit set ; Add " count ▁ * ▁ ( n ▁ - ▁ count ) ▁ * ▁ 2" to the answer ; Driver Code
< ? php function sumBitDifferences ( $ arr , $ n ) { $ ans = 0 ; for ( $ i = 0 ; $ i < 32 ; $ i ++ ) { $ count = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) if ( ( $ arr [ $ j ] & ( 1 << $ i ) ) ) $ count ++ ; $ ans += ( $ count * ( $ n - $ count ) * 2 ) ; } return $ ans ; } $ arr = array ( 1 , 3 , 5 ) ; $ n = sizeof ( $ arr ) ; echo sumBitDifferences ( $ arr , $ n ) , " STRNEWLINE " ; ? >