Given an integer X > 1 and an integer K > 0, the task is to find the greatest odd number < X such that the number of 1’s in its binary representation is at most K.
Input: X = 10, K = 2
Input: X = 29, K = 2
Naive Approach: Starting from X – 1 check all the numbers below X which have at most K set bits, the first number satisfying the condition is the required answer.
Efficient Approach: is to count the set bits. If the count is less than or equal to K, return X. Otherwise, keep removing righmost set bit while count – k does not become 0.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the largest number smaller than integer N with maximum number of set bits
- Find the largest number with n set and m unset bits
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if a number has same number of set and unset bits
- Same Number Of Set Bits As N
- Set all even bits of a number
- Set all odd bits of a number
- Number of times the largest perfect square number can be subtracted from N
- Toggle all odd bits of a number
- Set all the bits in given range of a number
- Swap bits in a given number
- Toggle all even bits of a number
- Rotate bits of a number
- Check whether the number has only first and last bits set
- Toggle all the bits of a number except k-th bit.
- For every set bit of a number toggle bits of other
- Check if all bits of a number are set
- Number with set bits only between L-th and R-th index
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.