Array containing power of 2 whose XOR and Sum of elements equals X | C ++ implementation of the above approach ; Function to return the required array ; Store the power of 2 ; while n is greater than 0 ; if there is 1 in binary representation ; Divide n by 2 Multiply p2 by 2 ; Driver code ; Get the answer ; Printing the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < long > getArray ( int n ) { vector < long > ans ; long p2 = 1 ; while ( n > 0 ) { if ( n & 1 ) ans . push_back ( p2 ) ; n >>= 1 ; p2 *= 2 ; } return ans ; } int main ( ) { long n = 15 ; vector < long > ans = getArray ( n ) ; for ( int i : ans ) cout << i << " ▁ " ; return 0 ; }