For example, I have a number 210 or 11010010 in binary, the 2nd 5th 7th and 8th position is 1, so the result is [2, 5, 7, 8].
What is the fastest way to find that?
For example, I have a number 210 or 11010010 in binary, the 2nd 5th 7th and 8th position is 1, so the result is [2, 5, 7, 8].
What is the fastest way to find that?
Just loop over your binary number to get the result.
a=format(210, 'b')
x=[]
for i in range(0,len(a)):
if a[i] == '1':
x.append(i+1)
1 position is [1, 2, 4, 7]
The fastest way is to precompute all combinations (only 256 of them) by whatever method, and store in a list (of lists).
You can build the list by appending 1 to all entries, then 2 to every other entries, then 3 to every fourth entries, and so on.
A solution in C++.
#include<iostream>
using namespace std;
int main()
{
int n=10;
int counter=1;
while(n)
{
if(n&1==1)
{
cout<<counter<<" ";
}
n=n>>1;
counter++;
}
}
Read a bit about bitwise shift and & operator, to understand the solution properly.