我正在解决一个 leetcode 问题,该问题需要编写一个公式来确定给定数字 n
的位字符串是否具有交替整数。
我觉得我的逻辑是可靠的,但我认为我定义位字符串并循环它的方式有问题。有人可以帮我找出为什么这段代码不起作用吗?谢谢,我是自学成才,这是我第一次尝试 javascript leetcode,所以任何建议都会受到赞赏!
//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
最佳答案
主要问题是您将 current
分配给 i,因此它的值从 1 到 n
的长度
另请注意,您可以在循环数组时循环遍历字符串,就像我在下面的代码片段中所做的那样
另请注意,您的中断位于代码的 else
部分之外。
在您的代码中,如果previous === current
,您可以return false
,然后节省一些时间
//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))
关于javascript - 位串中的交替整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71844753/