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
< ? php function findAndSum ( $ arr , $ n ) { $ sum = 0 ; $ mul = 1 ; for ( $ i = 0 ; $ i < 30 ; $ i ++ ) { $ count_on = 0 ; $ l = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( ( $ arr [ $ j ] & ( 1 << $ i ) ) > 0 ) if ( $ count_on ) $ l ++ ; else { $ count_on = 1 ; $ l ++ ; } else if ( $ count_on ) { $ sum += ( ( $ mul * $ l * ( $ l + 1 ) ) / 2 ) ; $ count_on = 0 ; $ l = 0 ; } } if ( $ count_on ) { $ sum += ( ( $ mul * $ l * ( $ l + 1 ) ) / 2 ) ; $ count_on = 0 ; $ l = 0 ; } $ mul *= 2 ; } return $ sum ; } $ arr = array ( 7 , 1 , 1 , 5 ) ; $ n = sizeof ( $ arr ) ; echo findAndSum ( $ arr , $ n ) ; ? >