Sum of Bitwise AND of all unordered triplets of an array | Java program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code
import java . util . * ; class GFG { static int tripletAndSum ( int [ ] arr , int n ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & ( 1 << bit ) ) != 0 ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = arr . length ; System . out . print ( tripletAndSum ( arr , N ) ) ; } }