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

159
Vistas
Enteros alternos en una cadena de bits

Estoy trabajando en una pregunta de leetcode que requiere escribir una fórmula que determine si una cadena de bits para un número dado n tiene enteros alternos.

Siento que mi lógica es sólida, pero creo que hay algo mal con la forma en que defino la cadena de bits y la recorro. ¿Puede alguien ayudarme a encontrar por qué este código no funciona? Gracias, soy autodidacta y esta es mi primera puñalada en un leetcode de javascript, ¡así que cualquier consejo es apreciado!

 //first we need to create a variable that is a string of the bits for whatever number is given //create variables current and previous and set them to null //create for loop that loops through each digit in the bit, and sets "current" the number being looped over //is that value = to previous (null on first loop)? no, continue loop and set previous to current //run through loop again, changing current value //is current = previous? if yes, result = false //if no, continue loop //define function var hasAlternatingBits = function(n) { let current = null; //set current to null so first loop iteration is always ture let previous = null; //previous is null so it can be changed during loop let result = true; //result is true until loop finds consecutive integers var bitString = n.toString(2).split(', '); //turn string into an array that can be looped //create for loop that loops entire string, or until it finds two consecutive integers for (let i = 0; i < bitString.length; i++) { //set value of current to number being looped over in string current = i; //if current doesnt equal previous, if (current !== previous) { previous = current; //set previous to current } else //if current does equal previous result = false; //change return to false break; //end loop } return result; }; console.log(hasAlternatingBits(5)) // should return true console.log(hasAlternatingBits(7)) // should return false

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

El principal problema era que le estabas asignando current a i, por lo que tomó el valor de 1 a la longitud de n

Tenga en cuenta también que puede recorrer la cadena mientras recorre la matriz como lo hice en el siguiente fragmento


Tenga en cuenta también que la ruptura estaba fuera de la else parte del código.

En su código, puede return false si previous === current y luego ahorrar algo de tiempo

 //define function var hasAlternatingBits = function(n) { let current = null; //set current to null so first loop iteration is always ture let previous = null; //previous is null so it can be changed during loop let result = true; //result is true until loop finds consecutive integers let bitString = n.toString(2);//turn into string //create for loop that loops entire string, or until it finds two consecutive integers for (let i = 0; i < bitString.length; i++) { //set value of current to number being looped over in string current = bitString[i]; // <-- here //if current doesnt equal previous, if (current !== previous) { previous = current;//set previous to current } else { //if current does equal previous return false } } return result; }; console.log(hasAlternatingBits(5)) console.log(hasAlternatingBits(7))

about 4 years ago · Santiago Gelvez Denunciar

0

Esta es mi oportunidad en esto:

 n == 0 || n.toString(2).split("").every((n, i) => n != i % 2)

Explicación:

every función iterará sobre la lista y acumulará los resultados verdaderos. Tiene el parámetro opcional i que es el índice del iterador. El resultado de i % 2 alterna entre 0 y 1 para valores crecientes de i.

 var fn = n => n == 0 || n.toString(2).split("").every((n, i) => n != i % 2) console.log(fn(5)) // true console.log(fn(7)) // false console.log(fn(11)) // false console.log(fn(21)) // true console.log(fn(0)) // true console.log(fn(1)) // true

about 4 years ago · Santiago Gelvez 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