Bitwise and ( or & ) of a range | Find position of MSB in n . For example if n = 17 , then position of MSB is 4. If n = 7 , value of MSB is 3 ; Function to find Bit - wise & of all numbers from x to y . ; res = 0 Initialize result ; Find positions of MSB in x and y ; If positions are not same , return ; Add 2 ^ msb_p1 to result ; subtract 2 ^ msb_p1 from x and y . ; Driver code
def msbPos ( n ) : NEW_LINE INDENT msb_p = - 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE msb_p += 1 NEW_LINE DEDENT return msb_p NEW_LINE DEDENT def andOperator ( x , y ) : NEW_LINE INDENT while ( x > 0 and y > 0 ) : NEW_LINE INDENT msb_p1 = msbPos ( x ) NEW_LINE msb_p2 = msbPos ( y ) NEW_LINE if ( msb_p1 != msb_p2 ) : NEW_LINE INDENT break NEW_LINE DEDENT msb_val = ( 1 << msb_p1 ) NEW_LINE res = res + msb_val NEW_LINE x = x - msb_val NEW_LINE y = y - msb_val NEW_LINE DEDENT return res NEW_LINE DEDENT x , y = 10 , 15 NEW_LINE print ( andOperator ( x , y ) ) NEW_LINE