Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
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 = maxNumExample
#include#include 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 Output
When you compile and execute above program. It generates following output −
Minimum required flips: 2
Advertisements
