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
function findAndSum ( arr , n ) { var sum = 0 ; var mul = 1 ; for ( var i = 0 ; i < 30 ; i ++ ) { var count_on = 0 ; var l = 0 ; for ( var 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 ; } var arr = [ 7 , 1 , 1 , 5 ] ; var n = arr . length ; document . write ( findAndSum ( arr , n ) ) ;