Given two non-negative numbers n and m. The problem is to find the smallest number having n number of set bits and m number of unset bits in its binary representation.
Constraints: 1 <= n, 0 <= m, (m+n) <= 31
Note : 0 bits before leading 1 (or leftmost 1) in binary representation are counted
Input : n = 2, m = 2 Output : 9 (9)10 = (1001)2 We can see that in the binary representation of 9 there are 2 set and 2 unsets bits and it is the smallest number. Input : n = 4, m = 1 Output : 23
Approach: Following are the steps:
- Calculate num = (1 << (n + m)) – 1. This will produce a number num having (n + m) number of bits and all are set.
- Now, toggle bits in the range from n to (n+m-1) in num, i.e, to toggle bits from the rightmost nth bit to the rightmost (n+m-1)th bit and then return the toggled number. Refer this post.
For greater values of n and m, you can use long int and long long int datatypes to generate the required number.
This article is contributed by Ayush Jauhari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Find the largest number with n set and m unset bits
- Count unset bits of a number
- Check if a number has same number of set and unset bits
- Unset the last m bits
- Unset bits in the given range
- Check whether all the bits are unset in the given range or not
- Count unset bits in a range
- Check whether all the bits are unset in the given range
- Smallest number whose set bits are maximum in a given range
- Python | Count unset bits in a range
- Count total unset bits in all the numbers from 1 to N
- M-th smallest number having k number of set bits.
- Find the largest number smaller than integer N with maximum number of set bits
- Program to find the Nth natural number with exactly two bits set
- Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
- Find K'th smallest number such that A + B = A | B
- Find smallest number n such that n XOR n+1 equals to given k.
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
Improved By : jit_t