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

174
Views
Check whether every item in an array is a power of 2

I can't seem to put this problem together,

Return an array containing all indices that are powers of 2

What I have below so far, I know modulo is probably the wrong operate, but I was trying to make it work. I'm not sure what else to try here.

function secondPower(arr) {
   
    let newarr = [];
  for(let i = 0; i < arr.length; i++){
    if(arr[i] / (2 ** i) === 1){
      newarr.push(i);
       }
  }
  return newarr;
}

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

0

You can use Math.log2 to check whether the number is a power of 2, and Array.every to check whether every item in the array matches a condition:

function isPowerOf2(x) {
    return Math.log2(x) % 1 === 0;
}

const arr = [1, 2, 4, 5, 7, 16]
const arr2 = [2, 4, 8]

function isArrAllPowerOf2(arr){
  return arr.every(isPowerOf2)
}

console.log(isArrAllPowerOf2(arr))
console.log(isArrAllPowerOf2(arr2))

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!