Given an integer , print the next smallest and next largest number that have the same number of 1 bits in their binary representation
After Counting the number of 1's in the number.How to determine the next smallest number?
Given an integer , print the next smallest and next largest number that have the same number of 1 bits in their binary representation
After Counting the number of 1's in the number.How to determine the next smallest number?
for next high you can use Hakmem 175 :
ITEM 175 (Gosper):
To get the next higher number with the same number of 1 bits:
unsigned nexthi_same_count_ones(unsigned a) {
/* works for any word length */
unsigned c = (a & -a);
unsigned r = a+c;
return (((r ^ a) >> 2) / c) | r;
}
For next lower I do not know a fast algorithm so I would use the classic approach, if the number is > then 2^0+2^1+...2^n then deduct one from your number and count the number of bits. The first number with n bits is the one.
For the smaller
int getNextSmaller(int num) {
return ~getNextLarger(~num);
}
Sometimes, things is just that simple. :)
Here is a very good explanation. :)
See for the sample number 156 below. I have also posted the source for detailed explanation.
{
x = 156
10011100 becomes 10100011
To get the next higher number we need to set the 6th bit from LSB and shift
the string of 1's (3rd,4th,5th) to LSB positions 1,2 and drop 5th bit
so we get 163 - 10100011, which is next highest number with same number of 1's as 156.
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163
}
{
uint_t snoob(uint_t x)
{
uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;
uint_t next = 0;
if(x){
// right most set bit
rightOne = x & -(signed)x;
// reset the pattern and set next higher bit
// left part of x will be here
nextHigherOneBit = x + rightOne;
// nextHigherOneBit is now part [D] of the above explanation.
// isolate the pattern
rightOnesPattern = x ^ nextHigherOneBit;
// right adjust pattern
rightOnesPattern = (rightOnesPattern)/rightOne;
// correction factor
rightOnesPattern >>= 2;
// rightOnesPattern is now part [A] of the above explanation.
// integrate new pattern (Add [D] and [A])
next = nextHigherOneBit | rightOnesPattern;
}
return next;
}
}
source: http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/