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