Wednesday, June 15, 2016

Given a number, find the next minimal greater number with same number of set bits
int GetNextNumCountBits(int n)
{
int count = countBits(n)
for (int i =n+1; i < INT_MAX;i++)
    if (countBits(i) == count)
       return i;
return 0
}
int countBits(n)
{
int count = 0;
while(n)
{
if (n&0x1) count++;
n >>=1;
}
return count;
}

/*geeksforgeeks mentions the following but it doesn't seem to work */
This problem has an interesting bit pattern that can be exploited for optimization
Take
155 for example
int nextOne(int x)
{
int rightOne;
int nextHigherOneBit
int rightOnesPattern;
int next = 0;
if (x)                                                                 //10011011
{
rightOne = x & -(signed)x;                              //00000001
nextHigherOneBit = x  + rightOne;                 //10011100
rightOnesPattern = x ^ nextHigherOneBit       //00000111
rightOnesPattern = (rightOnesPattern) / rightOne  //0000011 // right adjust by shifting 1 sequence except for leftmost
rightOnesPattern >> = 2                                   //00000001 // I'm skipping the above statement
next = nextHigherOneBit | rightOnesPattern   //10011101
}
return next;
}
157

If we want to right shift a number, we essentially divide by 2
5 = 101
5/2 = 2  => 10
2/2 => 1


Find the transition point between 0 and 1 in an infinite sorted sequence of binary
Int GetTransition (stream seq)
{
Int index = - 1;
Int power = 1
Int size = math.pow (2,i);
var buffer = new Sequence (size);
While(seq.read (buffer) != - 1)
     Index = find_binary_chop (buffer, size);
     If (Index! = - 1)
       Return index;
}
Return index;
}

No comments:

Post a Comment