Sum of bitwise AND of all possible subsets of given set | Python3 program to calculate sum of Bit - wise and sum of all subsets of an array ; assuming representation of each element is in 32 bit ; iterating array element ; Counting the set bit of array in ith position ; counting subset which produce sum when particular bit position is set . ; multiplying every position subset with 2 ^ i to count the sum . ; Driver code
BITS = 32 ; NEW_LINE def andSum ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , BITS ) : NEW_LINE INDENT countSetBits = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ j ] & ( 1 << i ) ) : NEW_LINE INDENT countSetBits = ( countSetBits + 1 ) NEW_LINE DEDENT DEDENT subset = ( ( 1 << countSetBits ) - 1 ) NEW_LINE subset = ( subset * ( 1 << i ) ) NEW_LINE ans = ans + subset NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE size = len ( arr ) NEW_LINE print ( andSum ( arr , size ) ) NEW_LINE