📜  复制范围内的设置位

📅  最后修改于: 2021-05-25 09:33:31             🧑  作者: Mango

给定两个数字x和y,以及范围[l,r],其中1 <= l,r <=32。该任务是考虑将y的位设置在[l,r]范围内,并将这些位也设置为x。例子 :

Input  : x = 10, y = 13, l = 2, r = 3
Output : x = 14
Binary representation of 10 is 1010 and 
that of y is 1101. There is one set bit
in y at 3’rd position (in given range). 
After we copy this bit to x, x becomes 1110
which is binary representation of 14.

Input  : x = 8, y = 7, l = 1, r = 2
Output : x = 11

资料来源:DE Shaw访谈

方法1(一一复制位)
通过遍历给定范围,我们可以一一找到y的设定位。对于每个设置位,我们将其与x的现有位进行“或”运算,以便如果未设置,则在x中设置。下面是C++的实现。

// C++ program to rearrange array in alternating
// C++ program to copy set bits in a given
// range [l, r] from y to x.
#include 
using namespace std;
  
// Copy set bits in range [l, r] from y to x.
// Note that x is passed by reference and modified
// by this function.
void copySetBits(unsigned &x, unsigned y,
                 unsigned l, unsigned r)
{
   // l and r must be between 1 to 32
   // (assuming ints are stored using
   //  32 bits)
   if (l < 1 || r > 32)
      return ;
  
   // Travers in given range
   for (int i=l; i<=r; i++)
   {
       // Find a mask (A number whose
       // only set bit is at i'th position)
       int mask = 1 << (i-1);
  
       // If i'th bit is set in y, set i'th
       // bit in x also.
       if (y & mask)
          x = x | mask;
   }
}
  
// Driver code
int main()
{
   unsigned x = 10, y = 13, l = 2, r = 3;
   copySetBits(x, y, l, r);
   cout << "Modified x is " << x;
   return 0; 
}

输出 :

Modified x is 14

方法2(使用一个位掩码复制所有位)

// C++ program to copy set bits in a given
// range [l, r] from y to x.
#include 
using namespace std;
  
// Copy set bits in range [l, r] from y to x.
// Note that x is passed by reference and modified
// by this function.
void copySetBits(unsigned &x, unsigned y,
                 unsigned l, unsigned r)
{
    // l and r must be between 1 to 32
    if (l < 1 || r > 32)
        return ;
  
    // get the length of the mask
    int maskLength = (1<<(r-l+1)) - 1;
  
    // Shift the mask to the required position
    // "&" with y to get the set bits at between
    // l ad r in y
    int mask = ((maskLength)<<(l-1)) & y ;
    x = x | mask;
}
  
// Driver code
int main()
{
   unsigned x = 10, y = 13, l = 2, r = 3;
   copySetBits(x, y, l, r);
   cout << "Modified x is " << x;
   return 0;
}

输出 :

Modified x is 14

感谢Ashish Rathi在评论中建议此解决方案。