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
< ? php function precompute ( & $ arr , $ n , & $ pre ) { $ pre [ $ n - 1 ] = $ arr [ $ n - 1 ] * pow ( 2 , 0 ) ; for ( $ 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 ) ) ; } $ arr = array ( 1 , 0 , 1 , 0 , 1 , 1 ) ; $ n = sizeof ( $ arr ) ; $ pre = array_fill ( 0 , $ n , NULL ) ; precompute ( $ arr , $ n , $ pre ) ; echo decimalOfSubarr ( $ arr , 2 , 4 , $ n , $ pre ) . " " ; echo decimalOfSubarr ( $ arr , 4 , 5 , $ n , $ pre ) . " " ; ? >