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

133
Views
Return an array containing all indices that are powers of 2

I'm working on this problem. Math is not one of strong suites. Any tips would be great. It is supposed to return an array of indices that are powers of 2.

function secondPower(arr) {
    // Return an array containing all indices that are powers of 2
    newArray = [];

    for(let i = 0; i < arr.length; i++){
        if(arr[i] % (2 ** i) === 0  && arr[i] != 1){
            newArray.push(arr[i]);
        }
    }
    return newArray;
}

An example of the solution is

secondPower([1, 2, 3, 4, 5, 6, 7, 8]) 

returns

[2,3,5]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using What is the best way to determine if a given number is a power of two?

const isPowerOf2 = v => v && !(v & (v - 1));
[1, 2, 3, 4, 5, 6, 7, 8].filter(isPowerOf2);

yields

[1, 2, 4, 8]
about 4 years ago · Juan Pablo Isaza Report

0

You can start at index 1 and keep multiplying by 2 until the value reaches the length of the array. This solution runs in logarithmic time and avoids a linear loop over all of the indexes.

function secondPower(arr) {
    const res = [];
    for(let i = 1; i < arr.length; i <<= 1) res.push(arr[i]);
    return res;
}
console.log(secondPower([1, 2, 3, 4, 5, 6, 7, 8]));

about 4 years ago · Juan Pablo Isaza Report

0

// if a number is a power of 2 its base 2 logarithm is an integer
const result = [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, v, i) => Number.isInteger(Math.log2(v)) ? a.concat(i) : a, []);
console.log(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!