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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- 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
- Find the largest number smaller than integer N with maximum number of set bits
- 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
- Check if all bits of a number are set
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.