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

162
Visualizações
Alternating Integers in a bit string

I am working on a leetcode question that requires writing a formula that determines whether or not a bit string for a given number n has alternating integers.

I feel like my logic is solid, but I think there is something wrong with the way I define the bit string and loop through it. Can someone help me find why this code is not working? Thanks, I am self taught and this is my first stab at a javascript leetcode, so any advice is appreciated!

//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 Respostas
Responde à pergunta

0

The main problem was that you were assigning current to i so it took the value from 1 to the length of n

Note also that you can loop through string as you loop through array as i did in the following snippet


Note also that you break was outside the else part of the code.

In your code you can just return false if previous === current and then save some time

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

0

This is my shot on this:

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

Explanation:

The every function will iterate over the list and accumulate the true results. It has the optional parameter i that is the iterator index. The result of i % 2 itself alternates between 0 and 1 for increasing values of 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 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