Given an integer N, the task is to find the greatest number that can be obtained by flipping at most K bits in the binary representation of N.
Input: N = 4, K = 1
The binary equivalent of 4 is 100.
On flipping the 1st 0, we get 110
which is equivalent to 6.
Input: N = 5, K = 2
- If the number of 0s in the binary representation of N is less than K then flip all the 0s.
- If the number of 0s is greater than or equal to K then flip the most significant K 0s.
- Finally, print the maximized integer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if all bits can be made same by flipping two consecutive bits
- Number formed by flipping all bits to the left of rightmost set bit
- Maximize distance between any two consecutive 1's after flipping M 0's
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Maximum number of consecutive 1s after flipping all 0s in a K length subarray
- Maximize number of elements from Array with sum at most K
- Largest number less than X having at most K set bits
- Minimum flips required to maximize a number with k set bits
- Maximize the number by rearranging 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
- Maximum score after flipping a Binary Matrix atmost K times
- Binary Matrix after flipping submatrices in given range for Q queries
- Minimize cost to convert a given matrix to another by flipping columns and reordering rows
- Maximize the profit by selling at-most M products
- Toggle all bits after most significant bit
- Minimum integer with at most K bits set such that their bitwise AND with N is maximum
- Maximize count of set bits in a root to leaf path in a binary tree
- Print numbers having first and last bits as the only set bits
- Next higher number with same number of set bits
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.