我试图找出为什么在以下方法中数组“8”中的最后一个值将满足“(8 & 7) == 0”的 where 子句。
public class Test {
public static void Main() {
int[] Arr = {-3, -1, 0, 1, 3, 8};
var s = from x in Arr where (x & (x-1)) == 0 select x+1;
foreach (int x in s)
Console.Write(x + " ");
}
}
它包含在招聘技能测试中,我一生都无法弄清楚为什么选择该值。不管怎样,我不会在测试中使用它,但我很好奇,因为我以前从未遇到过这个。
最佳答案
因此单个 &
是一个按位运算符。它正在查看这些数字的二进制表示形式。
7 = 0111 和 8 = 1000
当你将它们组合起来时,你会得到 0。
这就是为什么你的方法打印出 9。
关于c# - C# 如何评估数组循环 boolean 相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49886751/