Given a positive integer X the task is to find an integer Y such that:
- The count of set bits is Y is equal to the count of set bits in X.
- X != Y.
- |X – Y| is minimum.
Input: X = 92
90 is the closest number to 92 having
equal number of set bits.
Input: X = 17
Approach: A little math can lead us to the solution approach. Since the number of bits in both the numbers has to be the same, if a set bit is flipped then an unset bit will also have to be flipped.
Now the problem reduces to choosing two bits for the flipping. Suppose one bit at index i is flipped and another bit at index j (j < i) from the LSB (least significant bit). Then the absolute value of the difference between the original integer and the new one is 2i – 2j. To minimize this, i has to be as small as possible and j has to be as close to i as possible.
Since the number of set bits have to be equal, so the bit at index i must be different from the bit at index j. This means that the smallest can be the rightmost bit that's different from the LSB, and j must be the very next bit. In summary, the correct approach is to swap the two rightmost consecutive bits that are different.
Below is the implementation of the above approach:
Time Complexity: O(logn)
- Find the weight of the minimum spanning tree
- Find the multiple of x which is closest to a^b
- Find K Closest Points to the Origin
- Find the number closest to n and divisible by m
- Find the closest and smaller tidy number
- Find number from given list for which value of the function is closest to A
- Find multiple of x closest to or a ^ b (a raised to power b)
- Find a triplet in an array whose sum is closest to a given number
- Find One's Complement of an Integer
- Find whether a given integer is a power of 3 or not
- Find a pair (n,r) in an integer array such that value of nCr is maximum
- Find an integer in the given range that satisfies the given conditions
- Find a pair (n,r) in an integer array such that value of nPr is maximum
- Find an integer X which is divisor of all except exactly one element in an array
- Discrete logarithm (Find an integer k such that a^k is congruent modulo b)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.