布尔运算如何进行按位运算?

问题描述 投票:4回答:2

我在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

[我进行了一些研究,运算符'通过从左边向左推动最左边的位的副本向右移动,并让最右边的位掉落'。我认为我理解了(例如5 >> 1与0101 >> 1相同,其结果为0010),但是我看不到布尔值如何工作?我知道true的值为1,false的值为0。

javascript
2个回答
1
投票

按位运算符始终将其操作数转换为整数。因此,4 >> true4 >> 1相同,它将向右移一个位置

(decimal) 4 = (binary) 100

(binary) 100 >> 1 = (binary) 010

(binary) 010 = (decimal) 2

因此,使用truefalse只是使用10的一种round回方式。

notNotNot功能总体上非常简单:

  1. [a%2将第一个数字转换为偶数的0或奇数的1
  2. [>> b]向右移0false位置,或1true位置。
    • [a为奇数,bfalse = 1,因为向右移动了零,所以数字保持不变。
    • [a为奇数,btrue = 0,因为唯一的设置位1向右移位并被丢弃。
    • [a是偶数,bfalse = 0,因为向右移动了零,所以数字保持不变。
    • [a是偶数,btrue = 0,因为即使执行右移,基数也是0,没有设置任何位。
  3. !!()将结果转换为布尔值。

0
投票
(a%2)  //ignore all but the least significant bit (LSB)
(a%2 >> b )  //if TRUE,  shifts right, resolves to 0
               //if FALSE, no shift,     resolves to LSB

// 0 and LSB are both integers so convert to boolean by using logical/boolean NOT
!(a%2 >> b ) //resolves to the boolean which it is NOT
!!(a%2 >> b ) //resolves to the boolean which it is NOT NOT

NB对于任何布尔值,偶数个NOT会导致原始布尔值奇数个NOT会导致相反的布尔值

任何数字的最低位表示数字是奇数还是偶数。(0偶数,1奇数)

© www.soinside.com 2019 - 2024. All rights reserved.