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
def maxXorSum ( n , k ) : NEW_LINE INDENT if k == 1 : NEW_LINE INDENT return n NEW_LINE DEDENT res = 1 NEW_LINE while res <= n : NEW_LINE INDENT res <<= 1 NEW_LINE DEDENT return res - 1 NEW_LINE DEDENT n = 4 NEW_LINE k = 3 NEW_LINE print ( maxXorSum ( n , k ) ) NEW_LINE