Given two binary strings perform operation until B > 0 and print the result | JavaScript 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
let mod = ( 1e9 + 7 ) ; function BitOperations ( a , n , b , m ) { let ch1 = a . split ( ' ' ) ; ch1 . reverse ( ) ; a = ch1 . join ( " " ) ; let ch2 = b . split ( ' ' ) ; ch2 . reverse ( ) ; b = ch2 . join ( " " ) ; let c = 0 ; for ( let i = 0 ; i < m ; i ++ ) if ( b [ i ] == ' ' ) c ++ ; let power = new Array ( n ) ; power [ 0 ] = 1 ; for ( let i = 1 ; i < n ; i ++ ) power [ i ] = ( power [ i - 1 ] * 2 ) % mod ; let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == ' ' ) { ans += c * power [ i ] ; if ( ans >= mod ) ans %= mod ; } if ( b [ i ] == ' ' ) c -- ; if ( c == 0 ) break ; } return ans ; } let a = " " , b = " " ; let n = a . length , m = b . length ; document . write ( BitOperations ( a , n , b , m ) ) ;