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:
- Check if all bits can be made same by flipping two consecutive bits
- Maximize distance between any two consecutive 1's after flipping M 0's
- Maximize the number by rearranging bits
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Minimum flips required to maximize a number with k set 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 the number of palindromic Strings
- Check if a number has same number of set and unset bits
- Set all odd bits of a number
- Set all even bits of a number
- Same Number Of Set Bits As N
- Maximum score after flipping a Binary Matrix atmost K times
- Number with set bits only between L-th and R-th index
- Toggle first and last bits of a number
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.