Array containing power of 2 whose XOR and Sum of elements equals X
Last Updated :
15 Sep, 2022
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.
Examples:
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:
C++
#include <bits/stdc++.h>
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;
}
|
Java
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 + " " );
}
}
|
Python3
def getArray(n) :
ans = [];
p2 = 1 ;
while (n > 0 ) :
if (n & 1 ) :
ans.append(p2);
n >> = 1 ;
p2 * = 2 ;
return ans;
if __name__ = = "__main__" :
n = 15 ;
ans = getArray(n);
for i in ans :
print (i, end = " " );
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static List< long > getArray( int n)
{
List< long > ans = new List< 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;
List< long > ans = getArray(n);
foreach ( long i in ans)
Console.Write(i + " " );
}
}
|
Javascript
<script>
function getArray(n)
{
let ans = [];
let p2 = 1;
while (n > 0) {
if (n & 1)
ans.push(p2);
n >>= 1;
p2 *= 2;
}
return ans;
}
let n = 15;
let ans = getArray(n);
for (let i = 0; i < ans.length; i++)
document.write(ans[i] + " " );
</script>
|
Time Complexity: O(log2n)
Auxiliary Space: O(log2n)
Share your thoughts in the comments
Please Login to comment...