小编Rez*_*fin的帖子

所有对按位或总和

是否有一种算法可以在线性时间复杂度中找到按位或和或数组?

假设如果数组是 {1,2,3},那么所有对和 id 1|2 + 2|3 + 1|3 = 9。

我可以使用以下算法在 O(n) 中找到所有对 AND 总和......我如何更改它以获得所有对 OR 总和。

int ans = 0;  // Initialize result

// Traverse over all bits
for (int i = 0; i < 32; i++)
{
    // Count number of elements with i'th bit set
    int k = 0;  // Initialize the count
    for (int j = 0; j < n; j++)
        if ( (arr[j] & (1 << i)) )
            k++;

    // There are k set …
Run Code Online (Sandbox Code Playgroud)

bit-manipulation bit bitwise-or

2
推荐指数
1
解决办法
3850
查看次数

标签 统计

bit ×1

bit-manipulation ×1

bitwise-or ×1