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