Problem
Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.
Examples
Example 1:
|
|
Solution
Method 1 - Adding or subtracting 1 until we have same number of 1s
For the next largest, keep adding 1 to the number until find the number that has same number of 1 bits. For the next smallest, keep decreasing 1.
Code
|
|
|
|
Method 2- Change the bits
For getting the next higher number
-
Traverse from right to left i.e. LSB to MSB. Once we’ve passed a 1, turn on the next 0. We’ve now increased the number by
2^i
. Yikes! Example:xxxxx011100
becomesxxxxx111100
. -
Turn off the one that’s just to the right side of that. We’re now bigger by
2^i - 2^(i-1)
. Example:xxxxx111100
becomesxxxxx101100
-
Make the number as small as possible by rearranging all the 1s to be as far right as possible: Example:
xxxxx101100
becomesxxxxx100011
For the next smaller number We can do something like this.
|
|
i.e. follow the above algorithm for number’s complement.
Code
|
|