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
function maxXorSum ( n , k ) { if ( k == 1 ) return n ; let res = 1 ; while ( res <= n ) res <<= 1 ; return res - 1 ; } let n = 4 , k = 3 ; document . write ( maxXorSum ( n , k ) ) ;