【问题标题】:Efficient method using only bit-wise operations仅使用按位运算的有效方法
【发布时间】:2014-08-02 06:14:27
【问题描述】:

我们得到n 二进制数,每个k 位。我们需要找到一个k 位二进制数,其中ith 位仅在ith 位设置为n 给定二进制数之一时才设置。例如,

0010
0011
0100
1110

应该给1001 作为答案。您只需要使用按位运算来实现这一点。这是我的解决方案:

unsigned int array[n];//we have our 'n' numbers here
unsigned int answer=0,rxor=0,t1,t2;
for(int i=0; i<n; ++i)
{
     t1 = answer;
     answer ^= array[i];
     t2 = (~t1) & answer;
     answer &= ~(t2 & rxor);
     rxor |= array[i];
}

最终答案将存储在answer 变量中。它每次迭代总共使用7逐位操作(1 xor、1 or、2 negation、3 and),总共使用7*n操作。我的问题是,是否可以进一步减少操作次数。

【问题讨论】:

    标签: performance algorithm bit-manipulation


    【解决方案1】:

    要得出最终答案,您需要知道哪些位至少使用过一次,哪些位至少使用过两次。这两个条件可以很快计算出来:

    unsigned usedOnce = 0;
    unsigned usedTwice = 0;
    for(int i = 0; i < n; i++) {
        usedTwice |= usedOnce & array[i];
        usedOnce |= array[i];
    }
    unsigned answer = usedOnce & ~usedTwice;
    

    这只是循环中的三个操作。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2020-12-01
      • 2010-10-14
      相关资源
      最近更新 更多