Maximum XOR using K numbers from 1 to n | CPP program to find max xor sum of 1 to n using atmost k numbers ; 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 program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxXorSum ( int n , int k ) { if ( k == 1 ) return n ; int res = 1 ; while ( res <= n ) res <<= 1 ; return res - 1 ; } int main ( ) { int n = 4 , k = 3 ; cout << maxXorSum ( n , k ) ; return 0 ; }