Queries for decimal values of subarrays of a binary array | Fills pre [ ] ; returns the number represented by a binary subarray l to r ; if r is equal to n - 1 r + 1 does not exist ; Driver code
function precompute ( arr , n , pre ) { for ( let i = 0 ; i < n ; i ++ ) pre [ i ] = 0 ; pre [ n - 1 ] = arr [ n - 1 ] * ( Math . pow ( 2 , 0 ) ) ; for ( let i = n - 2 ; i >= 0 ; i -- ) pre [ i ] = pre [ i + 1 ] + arr [ i ] * ( 1 << ( n - 1 - i ) ) ; } function decimalOfSubarr ( arr , l , r , n , pre ) { if ( r != n - 1 ) return ( pre [ l ] - pre [ r + 1 ] ) / ( 1 << ( n - 1 - r ) ) ; return pre [ l ] / ( 1 << ( n - 1 - r ) ) ; } let arr = [ 1 , 0 , 1 , 0 , 1 , 1 ] ; let n = arr . length ; let pre = new Array ( n ) precompute ( arr , n , pre ) ; document . write ( decimalOfSubarr ( arr , 2 , 4 , n , pre ) + " " ) ; document . write ( decimalOfSubarr ( arr , 4 , 5 , n , pre ) ) ;