Powers of 2 to required sum using Bit Masking
Last Updated :
03 Jun, 2021
Given an integer N, the task is to find the numbers which when added after being raised to the Power of 2 gives the integer N.
Examples:
Input: N = 12345
Output: 0, 3, 4, 5, 12, 13
Explanation:
12345 = 2^0 + 2^3 + 2^4 + 2^5 + 2^12 + 2^13
Input: N = 10000
Output: 4, 8, 9, 10, 13
Explanation:
10000 = 2^4 + 2^8 + 2^9 + 2^10 + 2^13
Approach:
- Since every number can be expressed as sum of powers of 2, the task is to print every i when ith bit is set in the binary representation of N.
-
Illustration:
(29)10 = (11101)2
Thus, in 29, {0, 2, 3, 4} are the indices of the set bits.
20 + 22 + 23 + 24
= 1 + 4 + 8 + 16
= 29
-
- In order to check if ith bit is set, we only need to check:
if( N & (1 << i) ) == 1
Illustration:
(29)10 = (11101)2
0th bit: 11101 & 1 = 1
1st bit: 11101 & 10 = 0
2nd bit: 11101 & 100 = 1
3rd bit: 11101 & 1000 = 1
4th bit: 11101 & 10000 = 1
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void PowerOfTwo( long long N)
{
for ( int i = 0; i < 64; i++) {
long long x = 1;
if (N & (x << i))
cout << i << " " ;
}
}
int main()
{
long long N = 12345;
PowerOfTwo(N);
return 0;
}
|
Java
class GFG{
static void PowerOfTwo( long N)
{
for ( int i = 0 ; i < 64 ; i++)
{
long x = 1 ;
if ((N & (x << i)) > 0 )
System.out.print(i + " " );
}
}
public static void main(String[] args)
{
long N = 12345 ;
PowerOfTwo(N);
}
}
|
Python3
def PowerOfTwo(N):
for i in range ( 0 , 64 ):
x = 1
if (N & (x << i)) > 0 :
print (i, end = " " )
if __name__ = = "__main__" :
N = 12345 ;
PowerOfTwo(N)
|
C#
using System;
class GFG{
static void PowerOfTwo( long N)
{
for ( int i = 0; i < 64; i++)
{
long x = 1;
if ((N & (x << i)) > 0)
Console.Write(i + " " );
}
}
public static void Main()
{
long N = 12345;
PowerOfTwo(N);
}
}
|
Javascript
<script>
function PowerOfTwo(N)
{
for ( var i = 0; i < 64; i++) {
var x = 1;
if ((N & (x * Math.pow(2,i))) >0)
document.write( i + " " );
}
}
var N = 12345;
PowerOfTwo(N);
</script>
|
Time Complexity: O(log N)
Space Complexity: O(1)
For an alternative approach, refer to Powers of 2 to required sum
Share your thoughts in the comments
Please Login to comment...