Given two binary strings perform operation until B > 0 and print the result | Python 3 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
mod = 1000000007 NEW_LINE def BitOperations ( a , n , b , m ) : NEW_LINE INDENT a = a [ : : - 1 ] NEW_LINE b = b [ : : - 1 ] NEW_LINE c = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( b [ i ] == '1' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT power = [ None ] * n NEW_LINE power [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT power [ i ] = ( power [ i - 1 ] * 2 ) % mod NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] == '1' ) : NEW_LINE INDENT ans += c * power [ i ] NEW_LINE if ( ans >= mod ) : NEW_LINE INDENT ans %= mod NEW_LINE DEDENT DEDENT if ( b [ i ] == '1' ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = "1001" NEW_LINE b = "10101" NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( BitOperations ( a , n , b , m ) ) NEW_LINE DEDENT