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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With