gpt4 book ai didi

java - 查找数字奇偶性时出现意外值

转载 作者:行者123 更新时间:2023-11-30 06:54:51 26 4
gpt4 key购买 nike

以下代码来自《编程面试要点》,介绍如何查找数字的奇偶校验。

如果一个数中有奇数个 1,则该数的奇偶校验为 1。否则,它应该是 0。

1011 应返回 1

但是,书中的代码给出 0 代表 1011。我错过了什么?

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;
}

它是否忽略了符号位?

最佳答案

1011(十进制)是0b1111110011(二进制)。并且,具有偶数1位。

关于java - 查找数字奇偶性时出现意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com