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 . ; let 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
function msbPos ( n ) { let msb_p = - 1 ; while ( n > 0 ) { n = n >> 1 ; msb_p ++ ; } return msb_p ; } function andOperator ( x , y ) { while ( x > 0 && y > 0 ) { let msb_p1 = msbPos ( x ) ; let msb_p2 = msbPos ( y ) ; if ( msb_p1 != msb_p2 ) break ; let msb_val = ( 1 << msb_p1 ) ; res = res + msb_val ; x = x - msb_val ; y = y - msb_val ; } return res ; } let x = 10 , y = 15 ; document . write ( andOperator ( x , y ) ) ;