Sunday, July 28, 2013

Bit Flooding outward and backward of a set Bit...

FillBits:-

Consider a new bitwise binary operator that we will denote as x $ y. The result of this
operator is that the set bits of x "flood outwards" y bits to both the left and the right.
More precisely, the i-th bit (the least significant bit is considered to be the 0-th) of x $ y
will be 1 if and only if x has any bit whose value is 1 and whose position differs by at most
y from i (it can differ in either direction).


Write a program that given unsigned ints x and y, computes x $ y.


Example Inputs:
8 2
8 4
17 1


Outputs (respectively):
62
255
59


Explanation:
In the first case, 8 is 0000..00001000 in binary. The operation causes the only set bit in
the number to spread 2 positions in each direction, with a final result of 111110 (original
bit underlined), which is 62 in decimal.


In the second case, we spread the same bit 4 positions in each direction. This results in
4 1s to the left of the original bit's position. All 3 available positions to the right of the

original bit's position are filled (a 4th would normally be filled, but we have reached the
end of the number). The final number is 11111111, the value of which is 255.

In the third case, 17 is 10001 in binary, and spreading the 1s in each direction by 1 gives
111011, which is 59 in decimal.

With complexity:-K
#include<iostream>
using namespace std;
 
unsigned int FillBits(unsigned int x,unsigned int y)
{
    int i=0;
unsigned int a=x,b=x; 
while(y--)
{
a=a*2;   
b=b/2;
x=x|a|b;
}
 
return x;
}
int main(void)
{
unsigned int n,m;
cin>>n>>m;
cout<<FillBits(n,m);
return 0;
}

4 solution with complexity K
#include <iostream>
 
using namespace std;
 
unsigned int FillBits(unsigned int n,unsigned int y)
{
unsigned int k=0,m=1,p=0,r=0;
k=~(~k<<(2*y+1));
while(p<32)
{
  
  if(n&m)
  {
     if(p<y)
     {
         r=r|k>>(y-p);
         m=m<<1;
         p++;
     }
     else
     {
         r=r|k<<(p-y);
         m=m<<1;
         p=p+1;
     }
  }
  else
  {
  m<<=1;      
   p++;
  }
 
 
}
return r;
}
 
int main()
{  unsigned int x,y;
   cin>>x>>y;
   cout <<FillBits(x,y)<< endl; 
   
   return 0;
}

No comments:

Post a Comment