-2

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?

Duoduo
  • 479
  • 1
  • 4
  • 10
  • 2
    Please pick *one* programming language, the one you're working with. – CertainPerformance Oct 28 '18 at 10:45
  • Possible duplicate of [What are Python's equivalent of Javascript's reduce(), map(), and filter()?](https://stackoverflow.com/questions/31127824/what-are-pythons-equivalent-of-javascripts-reduce-map-and-filter) – mplungjan Oct 28 '18 at 10:46

4 Answers4

3
  1. Convert the number to binary:

    >>> format(210, 'b')
    '11010010'
    
  2. Use a list comprehension and enumerate to find the indices of the 1s:

    >>> [i for i, digit in enumerate(reversed('11010010'), 1) if digit == '1'] 
    [2, 5, 7, 8]
    
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

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]

Ankur Gulati
  • 291
  • 1
  • 12
0

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.

0

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.