Sum of bit differences among all pairs | package whatever do not write package name here ; int diff = 0 ; hold the ans ; XOR toggles the bits and will form a number that will have set bits at the places where the numbers bits differ eg : 010 ^ 111 = 101. . . diff of bits = count of 1 's = 2 ; when i == j ( same numbers ) the xor would be 0 , thus our ans will remain unaffected as ( 2 * 0 = 0 ) ; Kernighan algo ; int count = 0 ; ` count ` stores the total bits set in ` n ` ; n = n & ( n - 1 ) ; clear the least significant bit set
import java . io . * ; class GFG { static int sumBitDiff ( int [ ] arr ) { for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i ; j < arr . length ; j ++ ) { int xor = arr [ i ] ^ arr [ j ] ; diff += 2 * count ; } } return diff ; } static int countSetBits ( int n ) { while ( n != 0 ) { count ++ ; } return count ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 10 } ; int ans = sumBitDiff ( arr ) ; System . out . println ( ans ) ; } }