javascript - 按位运算如何在布尔值上工作?
问题描述
我在 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 >> 1
0010
true
1
false
0
解决方案
您提供的功能无法满足挑战。右移不会做要求的事情。例如,您的notNotNot(6,true)
is false
,而不是true
通过您的功能。
您的问题是关于布尔值的按位运算。由于运算符喜欢>>
并<<
处理整数,因此 Javascript 首先将布尔值转换为整数。Sotrue
变为 1 并false
变为 0。要看到这一点,您可以移动零:
console.log("true is",true >> 0)
console.log("false is", false >> 0)
Using!!
是将任何内容转换为布尔值的便捷方法。它接受任何被认为等同于 false 的东西(例如 0 null
、undefined
或 "")并返回false
。同样,任何真实的东西(如 14、“hello”、[4]、{a:1})和回馈true
。!!
之所以有效,是因为第一个感叹号给出了表达式的“不”,它总是true
or false
,然后第二个感叹号给出了相反的 ( false
or 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));
推荐阅读
- javascript - Vue 2 google-map 不会在故事书中呈现
- blazor - Blazor Web Assembly 项目未在浏览器中运行 (Edge/Chrome/IE)
- python - 如何使用matplotlib调整覆盖在图像上的networkx点的比例/轴?
- c# - C# 在哪里可以使用无参数构造函数获取 AWS 凭证
- python - Django + Okta + django_saml2_auth 禁止(未设置 CSRF cookie。)403
- c# - 使用 openxml 将行追加到 azure blob 存储中的 excel
- python - dll错误字符串在其他设备上运行带有模块的python应用程序
- image - 如何在 JavaFX 的 GridPane 中删除“幽灵线”?
- linux - 如何在 grafana 仪表板中隐藏主机?
- python - soup.findAll 返回一个空数组