简体   繁体   English

C ++:这些按位与与随后的比较有什么作用?

[英]C++: What do these bitwise AND's and following comparisons do?

I'm currently going through this implementation of finding a median using two heaps: No. 30 - Median in Stream 我目前正在通过两个堆来查找中位数的实现: 第30号-流中位数

I understand the general basic algorithm, but I'm not sure how this exact implementation works. 我了解通用的基本算法,但不确定这种确切的实现方式如何工作。 Specifically, I'm absolutely confused what these two lines do: 具体来说,我绝对对这两行的内容感到困惑:

if(((minHeap.size() + maxHeap.size()) & 1) == 0)
....
if(size & 1 == 1)

I believe I understand the bitwise AND- it takes the two numbers and outputs a number in binary. 我相信我了解按位AND,它接受两个数字并以二进制形式输出一个数字。 With the comparison of == 0 or == 1, it would check literally if the bitwise AND comes out with a 0 or a 1, respectively. 通过== 0或== 1的比较,它将逐字检查按位AND是否分别为0或1。 However, in the context of finding the median, what does this exactly do? 但是,在找到中位数的情况下,这究竟是做什么的? I know it's important for keeping the heaps "even" (and keeping the median in between the two heaps), but other than that I'm not entirely sure. 我知道保持堆“均匀”(并保持两个堆之间的中位数)很重要,但是除此之外,我不确定。 Is this really just a way to check if the sizes are different? 这真的是一种检查尺寸是否不同的方法吗?

I believe the first test is true if lowest bit is zero, ie sum is even number. 我相信如果最低位为零(即总和为偶数),则第一个测试是正确的。 The second test is true if size is odd number (ie LSB is set). 如果大小为奇数(即设置了LSB),则第二个测试为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM