【发布时间】:2017-06-22 06:18:13
【问题描述】:
以下代码来自 Elements of Programming Interview 中关于如何找到数字的奇偶性的代码。
如果一个数中有奇数个 1,则该数的奇偶性应为 1。否则应该为0。
1011 应该返回 1
但是,书中的代码为 1011 提供了 0。我错过了什么?
public static short parityBitByBitSmart(long x) {
short result = 0;
while(x != 0) {
result ^= 1;
x &= (x -1);
}
return result;
}
而且,我发现了另一个具有相同意外结果的代码示例
public static short parityBitByBit(long x) {
short result = 0;
while(x != 0) {
result ^= (x & 1);
x >>>= 1;
}
return result;
}
它是否忽略了符号位?
【问题讨论】:
-
没有“数字的奇偶性”这样的东西。奇偶校验可以定义为奇数或偶数,即添加位以使
1位的数量为奇数或偶数,具体取决于使用的奇偶校验方案。
标签: java bit-manipulation parity