Sum of bitwise AND of all subarrays | Java 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
class GFG { static int findAndSum ( int [ ] arr , int n ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { boolean count_on = false ; int l = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) if ( count_on ) l ++ ; else { count_on = true ; l ++ ; } else if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } } if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } mul *= 2 ; } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 1 , 1 , 5 } ; int n = arr . length ; System . out . println ( findAndSum ( arr , n ) ) ; } }