VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-flips-required-to-maximize-a-number-with-k-set-bits/

⇱ Minimum flips required to maximize a number with k set bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum flips required to maximize a number with k set bits

Last Updated : 23 May, 2022

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


 


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


 

Output : 
 

Min Flips = 3

Time Complexity: O(log2n), where n represents the given integer.
Auxiliary Space: O(1), no extra space is required, so it is a constant.


 

Comment
Article Tags:
Article Tags: