Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimum flips required to maximize a number with k set bits

  • Difficulty Level : Medium
  • Last Updated : 29 Apr, 2021

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. 
Note : K must be less than number of bits in n.
Examples : 
 

Input : n = 14, k = 2
Output : Min Flips = 1
Explanation : 
Binary representation of 14 = 1110
Largest 4-digit Binary number with
2 set bit = 1100
Conversion from 1110 to 1100 
requires 1 flipping

Input : n = 145, k = 4
Output : Min Flips = 3
Explanation : 
Binary representation of 145 = 10010001
Largest 8-digit Binary number with 
4 set bit = 11110000
Conversion from 10010001 to 11110000 
requires 3 flipping

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

For the given number n and k find the largest number possible with k-set bits and having exactly same number of bits as n has as : 
 



  • size = log2(n) + 1 gives the number of bits of n.
  • max = pow(2, k) – 1 gives largest possible number with k bits.
  • max = max << (size – k) gives the largest number possible with k-set bits and having exactly same number of bits as n has
  • Number of set bit in (n XOR max ) is our required number of flipping.

Illustration of above approach : 
 

let n = 145 (10010001), k = 4

size = log2(n) + 1 = log2(145) + 1 
                   = 7 + 1 = 8 

max = pow(2, k) -1 = pow(2, 4) - 1 
                   = 16 - 1 = 15 (1111) 

max = max << (size - k) = 15 << (8 - 4) 
                        = 240 (11110000)

number of set bit in  =  no. of set bit in 
(n XOR max )              (145 ^ 240 ) 
                      = 3

 

C++




// CPP for finding min flip
// for maximizing given n
#include <bits/stdc++.h>
using namespace std;
 
// function for finding set bit
int setBit(int xorValue)
{
    int count = 0;
    while (xorValue) {
        if (xorValue % 2)
            count++;
 
        xorValue /= 2;
    }
     
    // return count of set bit
    return count;
}
 
// function for finding min flip
int minFlip(int n, int k)
{  
    // number of bits in n
    int size = log2(n) + 1;
     
    // Find the largest number of
    // same size with k set bits
    int max = pow(2, k) - 1;   
    max = max << (size - k);
 
    // Count bit differences to find
    // required flipping.
    int xorValue = (n ^ max);
    return (setBit(xorValue));
}
 
// driver program
int main()
{
    int n = 27, k = 3;
    cout << "Min Flips = " << minFlip(n, k);
    return 0;
}

Java




// JAVA Code to find Minimum flips required
// to maximize a number with k set bits
import java.util.*;
 
class GFG {
     
    // function for finding set bit
    static int setBit(int xorValue)
    {
        int count = 0;
        while (xorValue >= 1) {
            if (xorValue % 2 == 1)
                count++;
      
            xorValue /= 2;
        }
          
        // return count of set bit
        return count;
    }
      
    // function for finding min flip
    static int minFlip(int n, int k)
    {  
        // number of bits in n
        int size = (int)(Math.log(n) /
                         Math.log(2)) + 1;
          
        // Find the largest number of
        // same size with k set bits
        int max = (int)Math.pow(2, k) - 1;   
        max = max << (size - k);
      
        // Count bit differences to find
        // required flipping.
        int xorValue = (n ^ max);
        return (setBit(xorValue));
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
         int n = 27, k = 3;
         System.out.println("Min Flips = "+
                             minFlip(n, k));
    }
}
 
// This code is contributed by Arnav Kr. Mandal.   

Python 3




# Python3 for finding min flip
# for maximizing given n
import math
 
# function for finding set bit
def setBit(xorValue):
 
    count = 0
    while (xorValue):
        if (xorValue % 2):
            count += 1
         
        xorValue = int(xorValue / 2)
         
    # return count
    # of set bit
    return count
 
# function for
# finding min flip
def minFlip(n, k):
 
    # number of bits in n
    size = int(math.log(n) /
               math.log(2) + 1)
     
    # Find the largest number of
    # same size with k set bits
    max = pow(2, k) - 1
    max = max << (size - k)
 
    # Count bit differences to
    # find required flipping.
    xorValue = (n ^ max)
    return (setBit(xorValue))
 
# Driver Code
n = 27
k = 3
print("Min Flips = " ,
        minFlip(n, k))
 
# This code is contributed
# by Smitha

C#




// C# Code to find Minimum flips required
// to maximize a number with k set bits
using System;
 
class GFG {
     
    // function for finding set bit
    static int setBit(int xorValue)
    {
        int count = 0;
        while (xorValue >= 1) {
            if (xorValue % 2 == 1)
                count++;
     
            xorValue /= 2;
        }
         
        // return count of set bit
        return count;
    }
     
    // function for finding min flip
    static int minFlip(int n, int k)
    {
        // number of bits in n
        int size = (int)(Math.Log(n) /
                         Math.Log(2)) + 1;
         
        // Find the largest number of
        // same size with k set bits
        int max = (int)Math.Pow(2, k) - 1;
        max = max << (size - k);
     
        // Count bit differences to find
        // required flipping.
        int xorValue = (n ^ max);
        return (setBit(xorValue));
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 27, k = 3;
        Console.Write("Min Flips = "+ minFlip(n, k));
    }
}
 
// This code is contributed by Nitin Mittal.

PHP




<?php
// PHP for finding min flip
// for maximizing given n
 
// function for finding set bit
function setBit($xorValue)
{
    $count = 0;
    while ($xorValue)
    {
        if ($xorValue % 2)
            $count++;
 
        $xorValue /= 2;
    }
     
    // return count of set bit
    return $count;
}
 
// function for finding min flip
function minFlip($n, $k)
{
    // number of bits in n
    $size = log($n) + 1;
     
    // Find the largest number of
    // same size with k set bits
    $max = pow(2, $k) - 1;
    $max = $max << ($size - $k);
 
    // Count bit differences to find
    // required flipping.
    $xorValue = ($n ^ $max);
    return (setBit($xorValue));
}
 
// Driver Code
$n = 27; $k = 3;
echo "Min Flips = " , minFlip($n, $k);
 
// This code is contributed by vt_m.
?>

Javascript




<script>
// Javascript for finding min flip
// for maximizing given n
 
// function for finding set bit
function setBit( xorValue)
{
    var count = 0;
    while (xorValue) {
        if (xorValue % 2)
            count++;
 
        xorValue = parseInt(xorValue / 2);
    }
     
    // return count of set bit
    return count;
}
 
// function for finding min flip
function minFlip(n, k)
{  
 
    // number of bits in n
    var size = Math.log2(n) + 1;
     
    // Find the largest number of
    // same size with k set bits
    var max = Math.pow(2, k) - 1;   
    max = (max << (size - k));
 
    // Count bit differences to find
    // required flipping.
    var xorValue = (n ^ max);
    return (setBit(xorValue));
}
 
// driver program
var n = 27, k = 3;
document.write( "Min Flips = " + minFlip(n, k));
 
// This code is contributed by itsok.
</script>

Output : 
 

Min Flips = 3

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!