Maximum XOR using K numbers from 1 to n | To return max xor sum of 1 to n using at most k numbers ; If k is 1 then maximum possible sum is n ; Finding number greater than or equal to n with most significant bit same as n . For example , if n is 4 , result is 7. If n is 5 or 6 , result is 7 ; Return res - 1 which denotes a number with all bits set to 1 ; Driver code
< ? php function maxXorSum ( $ n , $ k ) { if ( $ k == 1 ) return $ n ; $ res = 1 ; while ( $ res <= $ n ) $ res <<= 1 ; return $ res - 1 ; } $ n = 4 ; $ k = 3 ; echo maxXorSum ( $ n , $ k ) ; ? >