【问题标题】:Unexpected value for finding parity of a number查找数字奇偶性的意外值
【发布时间】: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


【解决方案1】:

1011(十进制)是0b1111110011(二进制)。而且,那个有一个偶数1位。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多