
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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
Advertisements