

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum flips required to maximize a number with k set bits in C++.
Problem statement
Given two numbers n and k, we need to find the minimum number of flips required to maximize given number by flipping its bits such that the resulting number has exactly k set bits. Please note input must satify condition that k < number of bits in n.
Example
Let us suppose n = 9 and k = 2
Binary representation of 9 is − 1001. It contains 4 bits.
Largest 4 digit binary number with 2 set bits is − 1100 i.e. 12
To convert 1001 to 1100 we have to flip highlighed 2 bits
Algorithm
1. Count the number of bits in n. Let us call this variable as bitCount. we can use log2(n) function from math library as fllows: bitCount = log2(n) + 1; 2. Find largest number with k set bits as follows: maxNum = pow(2, k) - 1; 3. Find the largest number possible with k set bits and having exactly same number of bits as n as follows: maxNum = maxNum << (bitCount - k); 4. Calculate (n ^ maxNum) and count number of set bits.
Example
#include <iostream> #include <cmath> using namespace std; int getSetBits(int n){ int cnt = 0; while (n) { ++cnt; n = n & (n - 1); } return cnt; } int minFlipsRequired(int n, int k){ int bitCount, maxNum, flipCount; bitCount = log2(n) + 1; maxNum = pow(2, k) - 1; maxNum = maxNum << (bitCount - k); flipCount = n ^ maxNum; return getSetBits(flipCount); } int main(){ cout << "Minimum required flips: " << minFlipsRequired(9, 2) << "\n"; return 0; }
Output
When you compile and execute above program. It generates following output −
Minimum required flips: 2
- Related Questions & Answers
- Minimum Number of K Consecutive Bit Flips in C++
- Program to find minimum number of flips required to have alternating values in Python
- Minimum number using set bits of a given number in C++
- Minimum number of bottles required to fill K glasses in C++
- Maximize the number by rearranging bits in C++
- Program to find minimum required chances to form a string with K unique characters in Python
- Count minimum right flips to set all values in an array in C++
- Program to maximize the minimum value after increasing K sublists in Python
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Largest number less than X having at most K set bits in C++
- Minimum Number of Flips to Convert Binary Matrix to Zero Matrix in C++
- C# program to count total set bits in a number
- Finding minimum flips in a binary string using JavaScript
- Program to find minimum number of bricks required to make k towers of same height in Python
Advertisements