Array containing power of 2 whose XOR and Sum of elements equals X | Java implementation 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
import java . util . * ; class GFG { static Vector < Long > getArray ( int n ) { Vector < Long > ans = new Vector < Long > ( ) ; long p2 = 1 ; while ( n > 0 ) { if ( n % 2 == 1 ) ans . add ( p2 ) ; n >>= 1 ; p2 *= 2 ; } return ans ; } public static void main ( String [ ] args ) { int n = 15 ; Vector < Long > ans = getArray ( n ) ; for ( Long i : ans ) System . out . print ( i + " ▁ " ) ; } }