簡體   English   中英

查找數字奇偶校驗的意外值

[英]Unexpected value for finding parity of a number

以下代碼來自 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;
}

它是否忽略了符號位?

1011 (十進制)是0b1111110011 (二進制)。 而且,偶數1位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM