Sum of bitwise AND of all subarrays | Python3 program to find Sum of bitwise AND of all subarrays ; Function to find the Sum of bitwise AND of all subarrays ; variable to store the final Sum ; multiplier ; variable to check if counting is on ; variable to store the length of the subarrays ; loop to find the contiguous segments ; updating the multiplier ; returning the Sum ; Driver Code
import math as mt NEW_LINE def findAndSum ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( 30 ) : NEW_LINE INDENT count_on = 0 NEW_LINE l = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) : NEW_LINE INDENT if ( count_on ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_on = 1 NEW_LINE l += 1 NEW_LINE DEDENT DEDENT elif ( count_on ) : NEW_LINE INDENT Sum += ( ( mul * l * ( l + 1 ) ) // 2 ) NEW_LINE count_on = 0 NEW_LINE l = 0 NEW_LINE DEDENT DEDENT if ( count_on ) : NEW_LINE INDENT Sum += ( ( mul * l * ( l + 1 ) ) // 2 ) NEW_LINE count_on = 0 NEW_LINE l = 0 NEW_LINE DEDENT mul *= 2 NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ 7 , 1 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findAndSum ( arr , n ) ) NEW_LINE