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

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

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 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