Given a number X, the task is to find the minimum number N such that total set bits of all numbers from 1 to n is atleast X.
Input: x = 5 Output: 4 Set bits in 1-> 1 Set bits in 2-> 1 Set bits in 3-> 2 Set bits in 4-> 1 Hence first four numbers add upto 5 Input: x = 20 Output: 11
Approach: Use binary search to get the minimum most number whose sum of bits till N is atleast X. At start, low is 0 and high is initialized according to the constraint. Check if count of set bits is atleast X, every time it is, change high to mid-1, else change it to mid+1. Everytime we do high = mid-1, store the minimal of answer.
Below is the implementation of the above approach:
Time Complexity: O(log N * log N)
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.
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
- Find out the minimum number of coins required to pay total amount
- Number of ways to change the XOR of two numbers by swapping the bits
- Minimum K such that every substring of length atleast K contains a character c
- Choose atleast two elements from array such that their GCD is 1 and cost is minimum
- Minimum window size containing atleast P primes in every window of given range
- Count of numbers whose 0th and Nth bits are set
- Find Bit whose minimum sequence flips makes all bits same
- Check if a number has same number of set and unset bits
- Check whether the number has only first and last bits set | Set 2
- Program to count number of set bits in an (big) array
- Number of mismatching bits in the binary representation of two integers
- Maximum and minimum of an array using minimum number of comparisons
- Leftmost Column with atleast one 1 in a row-wise sorted binary matrix
- Minimum sum of two numbers formed from digits of an array in O(n)
- Allocate minimum number of pages
- Reduce N to 1 with minimum number of given operations
- Minimum number to be added to all digits of X to make X > Y
- Minimum number of operations required to reduce N to 1
- Collect all coins in minimum number of steps
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.