Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda