Given two binary strings perform operation until B > 0 and print the result | PHP implementation of the approach ; Function to return the required result ; Reverse the strings ; Count the number of set bits in b ; To store the powers of 2 ; power [ i ] = pow ( 2 , i ) % mod ; To store the final answer ; Add power [ i ] to the ans after multiplying it with the number of set bits in b ; Divide by 2 means right shift b >> 1 if b has 1 at right most side than number of set bits will get decreased ; If no more set bits in b i . e . b = 0 ; Return the required answer ; Driver code
< ? php $ GLOBALS [ ' mod ' ] = ( 1e9 + 7 ) ; function BitOperations ( $ a , $ n , $ b , $ m ) { $ a = strrev ( $ a ) ; $ b = strrev ( $ b ) ; $ c = 0 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) if ( $ b [ $ i ] == '1' ) $ c ++ ; $ power = array ( ) ; $ power [ 0 ] = 1 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) $ power [ $ i ] = ( $ power [ $ i - 1 ] * 2 ) % $ GLOBALS [ ' mod ' ] ; $ ans = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ a [ $ i ] == '1' ) { $ ans += $ c * $ power [ $ i ] ; if ( $ ans >= $ GLOBALS [ ' mod ' ] ) $ ans %= $ GLOBALS [ ' mod ' ] ; } if ( $ b [ $ i ] == '1' ) $ c -- ; if ( $ c == 0 ) break ; } return $ ans ; } $ a = "1001" ; $ b = "10101" ; $ n = strlen ( $ a ) ; $ m = strlen ( $ b ) ; echo BitOperations ( $ a , $ n , $ b , $ m ) ; ? >