Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda