Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Given a non-negative integer, find the indexes of all the bits which are set to 1

Here is what I'm doing:

function getIndexes(n) {
    return n
        .toString(2)
        .split("")
        .map((c, i) => [c, i])
        .filter(([c, _]) => c == "1")
        .map(([_, i]) => i)
    ;
}

console.log(getIndexes(6));
console.log(getIndexes(7));
console.log(getIndexes(42));

Explanation:

  1. Convert the input number into a binary string
  2. Convert the binary string into an array of characters
  3. Map each character to a [character, index] tuple
  4. Filter (keep only) the tuples whose character is "1"
  5. Map each tuple to the index of that tuple

It feels a bit of an overkill.

Is there a more standard way to achieve that?

I care less about performance and more about using something cleaner and/or custom.

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If I well understood what you want to achieve, here is an alternative solution:

function getIndexes(n) {

  const result = [];

  const long_n = BigInt(n);

  for(let i = 0n; i < 64n; ++i) {

    if((long_n >> i) & 1n)  result.push(Number(i));

  }
  
  return result;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!