簡體   English   中英

二進制兩個連續的 1 位

[英]Binary two consecutive 1 bits

我試圖用 C 來實現,它在一個整數中輸出兩個連續的 1 位的數量而不重疊。 這是我的代碼:

#include <stdio.h>

int numPairs(int num) {
    int count = 0;
    while (num) {
        num = (num & (num << 1));
        count++;
    }
    return count / 2;
}

int main(){
    printf("%d\t", numPairs(10000));
    printf("%d\t", numPairs(146));
    printf("%d\t", numPairs(7645));
    printf("%d\t", numPairs(16383));
    return 0;
}

我的輸出是1 0 1 7

但輸出應該是1 0 3 7

除了7645 ,一切都是正確的,我不知道這有什么問題。

對於7645我的代碼給出了結果1但正確的結果是3

你的方法不合適:

您計算將表達式n = n & (n << 1);設為 null 所需的迭代次數n = n & (n << 1); . 這將是連續 1 位的最大數量。 如果位對是分開的,結果將與非重疊位對的數量不同。

76450x1ddd或十進制的0001 1101 1101 1101的情況下,有 3 組 3 個連續的 1 位,但它們在循環的 3 次並行迭代中被清零,因此count / 21

您必須使用不同的算法,例如:

int numPairs(int num) {
    int count = 0;
    unsigned int x = num;
    while (x) {
        if ((x & 3) == 3) {
            count++;
            x >>= 2;
        } else {
            x >>= 1;
        }
    }
    return count;
}

如果速度很重要,這也可以通過位操作操作來完成:

int numPairs(uint32_t x) {
    return __builtin_popcount((((x ^ 0x55555555) + 0x55555555) ^ 0x55555555) & x);
}

這會在每個不相交的 2 位 1 組的高位產生 1 位,然后對 1 位進行計數。

暫無
暫無

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

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