Given an integer X. The task is to find and return the array containing of powers of 2’s and the xor of the array is X.
Input: X = 20
Output: 16 4
Input: X = 15
Output: 1 2 4 8
Approach: The answer lies in the binary representation of the number X.
Since in the power of 2, there is only one set bit. If there are two distinct powers of 2’s present then the xor will be the addition of both the numbers.
Similarly, if xor of the whole array will be taken then it should be equal to X and that will be the binary representation of that number.
Since there is a distinct set bit in every power of 2’s, the xor and the sum of the elements of the array will be the same.
Below is the implementation of the above approach:
1 2 4 8
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count of n digit numbers whose sum of digits equals to given sum
- Print all n-digit numbers whose sum of digits equals to given sum
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- Minimize K whose XOR with given array elements leaves array unchanged
- Count triplet of indices (i, j, k) such that XOR of elements between [i, j) equals [j, k]
- Count of elements which cannot form any pair whose sum is power of 2
- Split an array containing N elements into K sets of distinct elements
- Find the sum of power of bit count raised to the power B
- Minimum number of squares whose sum equals to given number n
- Minimum number of squares whose sum equals to given number N | set 2
- Minimum number of squares whose sum equals to a given number N | Set-3
- Check if any permutation of N equals any power of K
- Number whose sum of XOR with given array range is maximum
- Number whose XOR sum with given array is a given number k
- Find smallest number n such that n XOR n+1 equals to given k.
- Number of pairs whose sum is a power of 2
- Count of elements to be inserted to make Array sum twice the XOR of Array
- Minimum element whose n-th power is greater than product of an array of size n
- Count pairs in Array whose product is a Kth power of any positive integer
- Find power of power under mod of a prime
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.