首页 > 解决方案 > 按位运算如何在布尔值上工作?

问题描述

我在 Edabit 上遇到了这个挑战,无法解决这个按位运算的解决方案。

notNotNot = (a,b) => !!(a%2 >> b)

挑战:

//Something which is not true is false, but something which is not not true is true! 
//Create a function where given n number of "not", evaluate whether it's true or false.

//Examples:
notNotNot(1, true) ➞ false
// Not true

notNotNot(2, false) ➞ false
// Not not false

notNotNot(6, true) ➞ true
// Not not not not not not true

我对该运营商进行了一些研究:

通过从左边推入最左边位的副本来右移,并让最右边的位脱落。

我认为我理解了(例如,与which 的计算结果5 >> 1相同),但我看不出它是如何与布尔值一起工作的?我知道评估 to和to 。0101 >> 10010true1false0

标签: javascript

解决方案


您提供的功能无法满足挑战。右移不会做要求的事情。例如,您的notNotNot(6,true)is false,而不是true通过您的功能。

您的问题是关于布尔值的按位运算。由于运算符喜欢>><<处理整数,因此 Javascript 首先将布尔值转换为整数。Sotrue变为 1 并false变为 0。要看到这一点,您可以移动零:

console.log("true is",true >> 0)
console.log("false is", false >> 0)
所以布尔值的按位运算实际上只是 0 或 1 的按位运算。

Using!!是将任何内容转换为布尔值的便捷方法。它接受任何被认为等同于 false 的东西(例如 0 nullundefined或 "")并返回false。同样,任何真实的东西(如 14、“hello”、[4]、{a:1})和回馈true!!之所以有效,是因为第一个感叹号给出了表达式的“不”,它总是trueor false,然后第二个感叹号给出了相反的 ( falseor true)。

回到挑战,它想应用非运算符“a”次并与“b”值进行比较。所以这样的事情会起作用:

function notNotNot(a, b) { return !!(a%2 - b); }
console.log("notNotNot(1, true)",notNotNot(1, true));
console.log("notNotNot(2, false)",notNotNot(2, false));
console.log("notNotNot(6, true)",notNotNot(6, true));


推荐阅读